e Learning

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, the str() function used to convert integers to strings.

str(int)

Example:

x = 10
x = str(10)

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

The Python programming language does not allow concatenating numbers with strings, for example.

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

The Above code will produce the 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 shown in the 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 be used to convert other data types to strings, including float, list, and dictionaries.