How to convert int to string in Python?


Type conversion is at times needed when the user wants to convert one data type into another data type according to requirement.

Python has in-built function str() to convert an integer to a string. We will be discussing various other methods in addition to this to convert int into string in Python.

Using str()

This is the most commonly used method to convert int into string in Python.The str() takes integer variable as a parameter and converts it into a string.

Syntax

str(integer variable)

Example

 Live Demo

num=2
print("Datatype before conversion",type(num))
num=str(num)
print(num)
print("Datatype after conversion",type(num))

Output

Datatype before conversion <class 'int'>
2
Datatype after conversion <class 'str'>

The type() function gives the datatype of the variable which is passed as parameter.

In the above code, before conversion, the datatype of num is int and after the conversion, the datatype of num is str(i.e. string in python).

Using f-string

Syntax

f ’{integer variable}’

Example

 Live Demo

num=2
print("Datatype before conversion",type(num))
num=f'{num}'
print(num)
print("Datatype after conversion",type(num))

Output

Datatype before conversion <class 'int'>
2
Datatype after conversion <class 'str'>

Using “%s” keyword

Syntax

“%s” % integer variable

Example

 Live Demo

num=2
print("Datatype before conversion",type(num))
num="%s" %num
print(num)
print("Datatype after conversion",type(num))

Output

Datatype before conversion <class 'int'>
2
Datatype after conversion <class 'str'>

Using .format() function

Syntax

‘{}’.format(integer variable)

Example

 Live Demo

num=2
print("Datatype before conversion",type(num))
num='{}'.format(num)
print(num)
print("Datatype after conversion",type(num))

Output

Datatype before conversion <class 'int'>
2
Datatype after conversion <class 'str'>

These were some of the methods to convert int into string in Python. We may require to convert int into string in certain scenarios such as appending value retained in a int into some string variable. One common scenario is to reverse an integer. We may convert it into string and then reverse which is easier than implementing mathematical logic to reverse an integer.

Updated on: 10-Mar-2021

936 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements