
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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
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
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.