Quick Reach
How to convert an int to string in Python?
As writing the code in Python, there will be scenarios when you will need to convert integers into a string.
An example of converting an int to string
Watch Video of this Tutorial
For example, if you need to concatenate a number to a string then you first need to convert that number into the string by using the built-in method.
Use Python str() method for converting integer to a string
The Python provides the str() method to convert integers into strings.
The str() method takes a parameter which is an integer. See the example below for learning how to convert a number into the string.
An example of str() method
In this example, two string variables are declared. Another variable which is an int type is declared and assigned a value.
Finally, the print() function is used where string variable is concatenated with the int variable. The int() variable is used in the str() method as shown below:
1
2
3
4
5
6
7
|
str1 = “This is Python Tutorial.”
str2 = “This is concatenation chapter”
int1 = 123
print (str1 + ” “ + str(int1))
|
The output will be:
This is Python Tutorial. 123
What happened if int was directly used?
If no str() method was used in above example, the 123 was taken as int and an error would have produced. See the code and output below:
1
2
3
4
5
6
7
|
str1 = “This is Python Tutorial.”
str2 = “This is concatenation chapter”
int1 = 123
print (str1 + ” “ + int1)
|
Leave A Comment?