How to convert Integer to String in Python
In this article, you are going to learn about how to convert an integer to a string in Python.
In the Python programming language, both integer and string are considered data types. The string data type is used to represent those data that are text-based.
On the other hand, the integer data type is used to represent the number-based data. Sometimes, you need to convert an integer type data into a string and to perform this action python provides the str() method. Along with this method, there are some other useful options like using %s, format() method and, f-string() method to convert an integer value to a string and in this article, we will explore them.
str() method
This is the most common and widely used approach for converting an integer value into a string. Here, all you need to do is to pass the integer value into the str() method. Let’s see the below code example:
age = 22
print(type(age))
# Using str() method
int_to_str = str(age)
print(type(int_to_str))
# Output:
# <class 'int'>
# <class 'str'>
Here, you can see that the value of age was in integer and we have converted it into the string by using the str() method and, to check this we are using type() that shows us the type of a value in python.
format() method
Another way of converting an integer value into a string is to use the format() method. It is almost similar to the str() method but has a little difference. See the below code example:
age = 22
print(type(age))
# Using format() method
int_to_str = "{}".format(age)
print(type(int_to_str))
# Output:
# <class 'int'>
# <class 'str'>
f-string literal
Another approach is to use the f-string literal for converting an integer value to a string. Here, f is referred to as formatted string literals. This is available in Python 3.6. See the below code example of using it.
age = 22
print(type(age))
# Using f-string literal
int_to_str = f'{age}'
print(type(int_to_str))
# Output:
# <class 'int'>
# <class 'str'>
%s operator
You may also use the %s operator to convert an integer value into a string and it’s very simple to use and this value defines to python that you want to add a string value. See the below code example:
age = 22
print(type(age))
# Using %s operator
int_to_str = "% s" % age
print(type(int_to_str))
# Output:
# <class 'int'>
# <class 'str'>
These are some useful approaches that you may follow for converting an integer value into a string in the Python programming language.