How to convert an integer to string in Python [Python convert int to string]

In this Python tutorial, we will discuss how to convert an integer to string in Python. Converting integers to strings is a common programming task, and Python provides several built-in functions and techniques to achieve this.

To convert an integer to string in Python, you can use various methods like the below:

  1. Using the str() function
  2. Using f-strings (formatted string literals)
  3. Using the format() method
  4. Using the %-formatting (printf-style string formatting)

Convert an integer to string in Python

Now, let us check out different methods to convert an integer to a string in Python with various examples.

1. Using the str() function

The str() function is a built-in Python function that converts its argument to a string representation.

Example:

number = 42
string_number = str(number)

print(string_number)
print(type(string_number))

Output:

42
<class 'str'>
convert an integer to string in Python
convert an integer to string in Python

2. Using f-strings (formatted string literals)

F-strings, also known as formatted string literals, were introduced in Python 3.6. They allow you to embed expressions inside string literals, using curly braces {}.

Example:

number = 42
string_number = f"{number}"

print(string_number)
print(type(string_number))

Output:

42
<class 'str'>

3. Using the format() method

The format() method is another way to format strings in Python. It allows you to replace placeholders, defined by curly braces {}, with the values of the variables passed as arguments.

Example:

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

print(string_number)
print(type(string_number))

Output:

42
<class 'str'>
convert number to string python
convert number to string python

4. Using the %-formatting

The %-formatting is an older method of string formatting, inspired by the printf-style in C. It uses the % operator followed by a format specifier to define the conversion between the data types.

Example:

number = 42
string_number = "%d" % number

print(string_number)
print(type(string_number))

Output:

42
<class 'str'>

Conclusion

In this tutorial, we learned four different methods to convert an integer to a string in Python:

  1. Using the str() function
  2. Using f-strings
  3. Using the format() method
  4. Using the %-formatting

All of these methods are valid and can be used interchangeably, depending on your preference and the Python version you are working with. F-strings and the str() function are the most modern and recommended ways of converting integers to strings in Python.

You may also like: