}

Python Convert Int to String: 6 Methods with Examples

Introduction

Converting an integer to a string is one of the most common operations in Python programming. Whether you're building output messages, logging data, or working with APIs, you'll frequently need to transform numeric values into text.

In this tutorial, you'll learn 6 different methods to convert an int to a string in Python, understand when to use each approach, and see performance comparisons to help you choose the best method for your use case.

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.

number = 42
result = str(number)

print(result)       # Output: 42
print(type(result)) # Output: <class 'str'>

Output:

42
<class 'str'>

This works with negative numbers and zero as well:

print(str(-100))  # Output: -100
print(str(0))     # Output: 0

When to use: This is the go-to method for simple integer to string conversion. It's readable, explicit, and works in all Python versions.

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

F-strings (formatted string literals) provide a concise and readable way to embed expressions inside string literals. They were introduced in Python 3.6.

number = 42
result = f"{number}"

print(result)       # Output: 42
print(type(result)) # Output: <class 'str'>

Output:

42
<class 'str'>

F-strings are particularly useful when you need to include the number in a larger string:

age = 25
message = f"I am {age} years old"
print(message)  # Output: I am 25 years old

You can also format numbers with f-strings:

number = 42
print(f"{number:05d}")   # Output: 00042 (zero-padded)
print(f"{number:+d}")    # Output: +42 (with sign)
print(f"{number:,}")     # Output: 42 (with thousand separator for larger numbers)

big_number = 1000000
print(f"{big_number:,}") # Output: 1,000,000

When to use: Preferred when embedding integers in strings or when you need formatting options. Requires Python 3.6+.

Method 3: Using .format() Method

The format() method is an older but still widely used approach that works in Python 2.6+ and all Python 3 versions.

number = 42
result = "{}".format(number)

print(result)       # Output: 42
print(type(result)) # Output: <class 'str'>

Output:

42
<class 'str'>

You can also use named placeholders:

result = "{value}".format(value=42)
print(result)  # Output: 42

Or positional arguments:

result = "{0} and {1}".format(10, 20)
print(result)  # Output: 10 and 20

When to use: When you need compatibility with older Python versions or when working with dynamic format strings.

Method 4: Using % Formatting (Old Style)

The % operator is the oldest string formatting method in Python. While considered outdated, you'll still encounter it in legacy codebases.

number = 42
result = "%s" % number

print(result)       # Output: 42
print(type(result)) # Output: <class 'str'>

Output:

42
<class 'str'>

For explicit integer formatting, use %d:

number = 42
result = "%d" % number
print(result)  # Output: 42

# With padding
print("%05d" % number)  # Output: 00042
print("%-5d" % number)  # Output: 42   (left-aligned)

When to use: Only when maintaining legacy code. For new projects, prefer str(), f-strings, or .format().

Method 5: repr() vs str()

Both repr() and str() convert integers to strings, but they serve different purposes.

number = 42

str_result = str(number)
repr_result = repr(number)

print(str_result)   # Output: 42
print(repr_result)  # Output: 42

For integers, the output is identical. The difference becomes apparent with other types:

text = "Hello\nWorld"

print(str(text))   # Output: Hello
                   #         World

print(repr(text))  # Output: 'Hello\nWorld'

Key differences:

Function Purpose Use Case
str() Human-readable output Display to users
repr() Developer-readable output Debugging, logging

When to use repr(): For debugging purposes or when you need an unambiguous representation of an object.

Method 6: Converting to Different Bases

Python provides built-in functions to convert integers to strings in binary, octal, and hexadecimal formats.

Binary (Base 2)

number = 42

binary = bin(number)
print(binary)        # Output: 0b101010
print(type(binary))  # Output: <class 'str'>

# Without the '0b' prefix
print(bin(number)[2:])  # Output: 101010

# Using format()
print(format(number, 'b'))  # Output: 101010

Octal (Base 8)

number = 42

octal = oct(number)
print(octal)  # Output: 0o52

# Without the '0o' prefix
print(oct(number)[2:])      # Output: 52
print(format(number, 'o'))  # Output: 52

Hexadecimal (Base 16)

number = 42

hexadecimal = hex(number)
print(hexadecimal)  # Output: 0x2a

# Without the '0x' prefix
print(hex(number)[2:])      # Output: 2a
print(format(number, 'x'))  # Output: 2a (lowercase)
print(format(number, 'X'))  # Output: 2A (uppercase)

Custom Base Conversion

For bases other than 2, 8, 10, or 16, you can use numpy.base_repr() or implement your own function:

def int_to_base(number, base):
    if number == 0:
        return "0"

    digits = ""
    is_negative = number < 0
    number = abs(number)

    while number:
        digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[number % base] + digits
        number //= base

    return "-" + digits if is_negative else digits

print(int_to_base(42, 5))   # Output: 132
print(int_to_base(255, 16)) # Output: FF

Common Errors and Edge Cases

TypeError: Can't Convert Non-Integer Types Directly

When concatenating strings with integers, you must convert explicitly:

# This will raise TypeError
age = 25
# message = "Age: " + age  # TypeError!

# Correct approaches
message = "Age: " + str(age)
message = f"Age: {age}"
message = "Age: {}".format(age)

Handling None Values

value = None

# str() handles None gracefully
result = str(value)
print(result)  # Output: None

# Be careful with conditional conversion
value = None
result = str(value) if value is not None else "N/A"
print(result)  # Output: N/A

Large Integers

Python handles arbitrarily large integers seamlessly:

big_number = 10**100  # A googol
result = str(big_number)
print(len(result))  # Output: 101 (100 zeros + 1)

Boolean Values

Booleans are a subclass of integers in Python:

print(str(True))   # Output: True
print(str(False))  # Output: False

# If you want 1 or 0
print(str(int(True)))   # Output: 1
print(str(int(False)))  # Output: 0

Performance Comparison

Let's compare the performance of different methods:

import timeit

number = 12345

# Test each method
methods = {
    'str()': lambda: str(number),
    'f-string': lambda: f"{number}",
    'format()': lambda: "{}".format(number),
    '% formatting': lambda: "%s" % number,
    'repr()': lambda: repr(number),
}

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

Typical results (may vary by system):

str(): 0.0852 seconds
f-string: 0.0912 seconds
format(): 0.1534 seconds
% formatting: 0.1248 seconds
repr(): 0.0867 seconds

Key takeaways:

  • str() and repr() are the fastest options
  • f-strings are nearly as fast and offer better readability
  • .format() is the slowest but most flexible
  • For most applications, the performance difference is negligible

Quick Reference Table

Method Syntax Python Version Best For
str() str(42) All Simple conversion
f-string f"{42}" 3.6+ Embedding in strings
.format() "{}".format(42) 2.6+ Dynamic formatting
% "%s" % 42 All Legacy code
repr() repr(42) All Debugging
bin() bin(42) All Binary representation
oct() oct(42) All Octal representation
hex() hex(42) All Hexadecimal representation

Summary

Converting an integer to a string in Python is straightforward with multiple methods available:

  1. Use str() for simple, explicit conversion — it's the most readable and universally compatible
  2. Use f-strings when embedding numbers in larger strings (Python 3.6+)
  3. Use .format() for complex formatting or older Python versions
  4. Use % formatting only for maintaining legacy code
  5. Use bin(), oct(), hex() for base conversions

For most use cases, str() is the recommended approach due to its simplicity and clarity. When building strings with multiple variables, f-strings offer the best combination of readability and performance.