How to convert int to string in Python

1. Using the str() function

The str() function is a built-in function in Python that converts an object into its string representation. For an integer, it returns the number as a string.

Syntax

str(object)
  • object: This is the data you want to convert to a string. In your case, it would be an integer.

Example

num = 123
num_str = str(num)
print(num_str)  # Output: '123'
print(type(num_str))  # Output: <class 'str'>

In this example:

  1. num is an integer.
  2. str(num) converts it to the string '123'.

2. Why use str()?

  • Readability: The str() function is simple and intuitive for converting to strings.
  • Compatibility: It works on various data types, including integers, floats, and objects that implement the __str__ method.

3. Other Methods for Conversion

Using f-strings (Python 3.6 and later)

An f-string is a formatted string literal. You can embed expressions inside string literals prefixed with f.

Example

num = 456
num_str = f"{num}"
print(num_str)  # Output: '456'
print(type(num_str))  # Output: <class 'str'>
  • Here, {num} is evaluated and converted into a string automatically.

Using String Concatenation

When you concatenate an integer with a string using the + operator, Python will raise a TypeError. However, explicitly converting the integer to a string avoids this.

Example

num = 789
num_str = str(num) + " is now a string"
print(num_str)  # Output: '789 is now a string'

Using repr()

The repr() function also converts objects to their string representation, but it includes quotes for strings and more details for other objects. For integers, it behaves similarly to str().

Example

num = 101
num_repr = repr(num)
print(num_repr)  # Output: '101'
print(type(num_repr))  # Output: <class 'str'>

When to Use Which Method?

  • Use str() for general purposes.
  • Use f-strings for formatted output or embedding values in a string.
  • Use repr() if you need a representation that is closer to how the object is displayed in Python code.