}

How to Convert Int to String in Python [5 Methods with Examples]

Introduction

Converting an integer to a string in Python is one of the most common operations you'll perform as a developer. Whether you're building user interfaces, logging data, or formatting output, knowing how to convert int to string in Python is essential.

In this comprehensive tutorial, we'll cover five different methods to convert integers to strings, with practical examples and a performance comparison to help you choose the best approach for your needs.

Method 1: Using str() Function (Recommended)

The str() function is the most straightforward and commonly used method to convert an integer to a string in Python:

# Basic conversion
number = 42
text = str(number)
print(text)        # Output: '42'
print(type(text))  # Output: <class 'str'>

Using str() with Variables

# With variables
age = 25
message = "I am " + str(age) + " years old"
print(message)  # Output: I am 25 years old

# Converting negative numbers
negative = -100
print(str(negative))  # Output: '-100'

# Converting zero
print(str(0))  # Output: '0'

How str() Works Internally

When you call str(object), Python invokes the object's __str__() magic method. For integers, this returns the decimal string representation:

# These are equivalent
number = 123
print(str(number))           # Output: '123'
print(number.__str__())      # Output: '123'

Method 2: Using f-strings (Python 3.6+)

F-strings (formatted string literals) provide a concise and readable way to embed expressions inside strings:

# Basic f-string conversion
number = 42
text = f"{number}"
print(text)  # Output: '42'

# Combining with other text
age = 30
name = "Alice"
message = f"{name} is {age} years old"
print(message)  # Output: Alice is 30 years old

F-string Formatting Options

F-strings offer powerful formatting capabilities:

number = 42

# Padding with zeros
print(f"{number:05}")    # Output: '00042'

# Adding thousands separator
large = 1000000
print(f"{large:,}")      # Output: '1,000,000'

# Specifying width
print(f"{number:10}")    # Output: '        42'

# Left-aligned with width
print(f"{number:<10}")   # Output: '42        '

# Binary, octal, hexadecimal
print(f"{number:b}")     # Output: '101010' (binary)
print(f"{number:o}")     # Output: '52' (octal)
print(f"{number:x}")     # Output: '2a' (hexadecimal)
print(f"{number:X}")     # Output: '2A' (uppercase hex)

Method 3: Using format() Function

The format() function provides similar capabilities to f-strings but works with Python 2.6+:

# Basic format conversion
number = 42
text = format(number)
print(text)  # Output: '42'

# Using format specifications
print(format(number, '05'))    # Output: '00042'
print(format(number, 'b'))     # Output: '101010'
print(format(number, 'x'))     # Output: '2a'

Using str.format() Method

The str.format() method allows placeholder substitution:

# Basic placeholder
template = "The number is {}"
result = template.format(42)
print(result)  # Output: The number is 42

# Multiple placeholders
template = "{} + {} = {}"
result = template.format(2, 3, 5)
print(result)  # Output: 2 + 3 = 5

# Named placeholders
template = "{name} has {count} items"
result = template.format(name="Alice", count=5)
print(result)  # Output: Alice has 5 items

Method 4: Using % Operator (Legacy Method)

The percent operator is the oldest string formatting method in Python. While still supported, it's considered legacy:

# Basic % formatting
number = 42
text = "%d" % number
print(text)  # Output: '42'

# Multiple values (use tuple)
result = "%d + %d = %d" % (2, 3, 5)
print(result)  # Output: 2 + 3 = 5

# Formatting options
print("%05d" % number)    # Output: '00042'
print("%10d" % number)    # Output: '        42'
print("%-10d" % number)   # Output: '42        '

Common Format Specifiers

Specifier Description Example
%d Integer 42 → '42'
%i Integer 42 → '42'
%o Octal 42 → '52'
%x Hexadecimal (lowercase) 42 → '2a'
%X Hexadecimal (uppercase) 42 → '2A'

Method 5: Using repr() Function

The repr() function returns a string representation suitable for debugging:

# Basic repr conversion
number = 42
text = repr(number)
print(text)  # Output: '42'
print(type(text))  # Output: <class 'str'>

Difference Between str() and repr()

For integers, str() and repr() produce identical results. However, they differ for other types:

# For integers - same result
number = 42
print(str(number))    # Output: 42
print(repr(number))   # Output: 42

# For strings - different result
text = "Hello"
print(str(text))      # Output: Hello
print(repr(text))     # Output: 'Hello' (includes quotes)

Performance Comparison

Let's compare the performance of different conversion methods:

import timeit

number = 42

# Test each method
methods = {
    'str()': 'str(42)',
    'f-string': 'f"{42}"',
    'format()': 'format(42)',
    '% operator': '"%d" % 42',
    'repr()': 'repr(42)',
}

for name, code in methods.items():
    time = timeit.timeit(code, number=1000000)
    print(f"{name:15}: {time:.4f} seconds")

Typical results (may vary by Python version and system):

str()          : 0.0821 seconds
f-string       : 0.0634 seconds
format()       : 0.1245 seconds
% operator     : 0.0987 seconds
repr()         : 0.0856 seconds

Key findings: - F-strings are typically the fastest - str() is a close second and more explicit - format() is slower but most flexible - Use str() for simple conversions, f-strings for formatting

Common Errors and Solutions

Error 1: AttributeError with .str()

# WRONG - integers don't have a .str() method
number = 42
text = number.str()  # AttributeError!

# CORRECT - use str() function
text = str(number)

Error 2: TypeError in Concatenation

# WRONG - can't concatenate str and int
age = 25
message = "Age: " + age  # TypeError!

# CORRECT - convert int to str first
message = "Age: " + str(age)

# BETTER - use f-string
message = f"Age: {age}"

Error 3: Confusing int() and str()

# int() converts string to integer
text = "42"
number = int(text)  # 42 (integer)

# str() converts integer to string
number = 42
text = str(number)  # "42" (string)

Practical Examples

Example 1: Building File Names

# Creating numbered file names
for i in range(1, 6):
    filename = f"report_{i:03}.txt"
    print(filename)
# Output:
# report_001.txt
# report_002.txt
# report_003.txt
# report_004.txt
# report_005.txt

Example 2: Logging with Timestamps

import time

def log_message(message, code):
    timestamp = int(time.time())
    log_entry = f"[{timestamp}] Code {code}: {message}"
    print(log_entry)

log_message("Operation completed", 200)
# Output: [1707728400] Code 200: Operation completed

Example 3: Formatting Currency

def format_price(cents):
    dollars = cents // 100
    remaining_cents = cents % 100
    return f"${dollars}.{remaining_cents:02}"

print(format_price(1299))   # Output: $12.99
print(format_price(500))    # Output: $5.00
print(format_price(99))     # Output: $0.99

Summary

Python offers multiple ways to convert integers to strings:

Method Best For Python Version
str() Simple conversions All versions
f-strings Formatted output 3.6+
format() Complex formatting 2.6+
% operator Legacy code All versions
repr() Debugging All versions

Recommendations: - Use str() for simple conversions - Use f-strings for formatted output (Python 3.6+) - Avoid % operator in new code - Use repr() only for debugging purposes

More Resources