Converting integer to string in Python
I want to convert an integer to a string in Python. I am typecasting it in vain:
d = 15
d.str()
When I try to convert it to string, it's showing an error like int
doesn't have any attribute called str
.
Solution 1:
>>> str(10)
'10'
>>> int('10')
10
Links to the documentation:
-
int()
str()
Conversion to a string is done with the builtin str()
function, which basically calls the __str__()
method of its parameter.
Solution 2:
Try this:
str(i)
Solution 3:
There is not typecast and no type coercion in Python. You have to convert your variable in an explicit way.
To convert an object in string you use the str()
function. It works with any object that has a method called __str__()
defined. In fact
str(a)
is equivalent to
a.__str__()
The same if you want to convert something to int, float, etc.