How to Convert integers to strings in Python 3

Often you will need to convert integers to strings in python programming, especially if you want to concatenate integers with strings. In this tutorial we are going to learn how to convert python int to string in python 3.

In python 3 str() function used to convert integers to strings.

str(int)

 

Example :

x = 10
print(type(x))
x = str(10)
print(type(x))

In the Above example, str() function will convert variable x to a string. We can verify this by using, the type() function.

x = 10
print(type(x))
x = str(10)
print(type(x))

This will output

<class 'int'>
<class 'str'>

Concatenate Numbers and Strings in Python 3

Python programing language does not allow to Concatenate numbers with strings, for example.

age = 10
print("Age is " + age)

The Above code will produce following error

TypeError: Can't convert 'int' object to str implicitly

So we need to convert the int variable age to string using the python str() function, as below example.

age = 10
print("Age is " + str(age))

This will output

Age is 10

Python 3 String Formatting

If you want to add numbers within a string without converting, then you have to use the python 3 format() method.

num1 = 10
num2 = 20

print("num1 is {} and num2 is {} ".format(num1, num2))

In the above example, format() function will replace curly braces inside the string ("{}") with num1 and num2 respectively. The code will output.

num1 is 10 and num2 is 20 

 

Python 3 str() function can also use to convert other data types to strings, including float, list and dictionaries.