To convert an integer to a string, Python uses the str() function. This function takes one argument (e.g. integer) and converts it into a string. This value can be displayed as an output or merged with other string values.
Look at this example:
1 |
age = str(46) |
It’s the same as:
1 |
age = '46' |
Printing the result
If you want to just display a number, you don’t have explicitly convert an integer to string, the print function will do it for you.
This works:
1 2 |
age = str(46) print(age) |
But this also works:
1 2 |
age = 46 print(age) |
Python offers the type function to check the type of variable.
1 2 3 4 5 6 7 |
a = 12 b = str(12) c = '12' print(type(a)) print(type(b)) print(type(c)) |
This will display the following results:
<class 'int'> <class 'str'> <class 'str'>
Joining strings and integers
The problem starts when you need to join variables with other string. Now, you can’t use the int variable without explicit conversion.
The following code won’t work:
1 2 |
age = 46 print('He is ' + age + ' years old') |
But after converting the value to string it works flawlessly:
1 2 |
age = str(46) print('He is ' + age + ' years old') |
You can also convert the value inside the print function:
1 2 |
age = 46 print('He is ' + str(age) + ' years old') |
The format function
The str function is useful when you want to convert one, or two values, but when you have more of them you may want to use the format function.
Here’s how it works:
1 2 3 4 5 |
name = 'John' age = 45 kids = 4 print("{0} is {1} years old and has {2} kids.".format(name, age, kids)) |
This code will generate the following message:
John is 45 years old and has 4 kids.
There is a different version of this code. Instead of using indexes, you can specify names.
1 2 3 4 5 |
name = 'John' age = 45 kids = 4 print("{name} is {age} years old and has {number_of_kids} kids.".format(name=name, age=age, number_of_kids=kids)) |
This code will generate the same result as the code before.