The Python Oracle

Convert integer to string in Python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping

--

Chapters
00:00 Question
00:41 Accepted answer (Score 2309)
01:05 Answer 2 (Score 149)
01:16 Answer 3 (Score 68)
01:52 Answer 4 (Score 20)
02:06 Thank you

--

Full question
https://stackoverflow.com/questions/9616...

Question links:
[How do I parse a string to a float or int?]: https://stackoverflow.com/questions/3799.../
[floating-point values are not precise]: https://stackoverflow.com/questions/5880.../
[Converting a float to a string without rounding it]: https://stackoverflow.com/questions/1317...

Accepted answer links:
[int()]: https://docs.python.org/3/library/functi...
[str()]: https://docs.python.org/3/library/functi...
[__str__()]: https://docs.python.org/3/reference/data...
[repr(x)]: https://docs.python.org/3/library/functi...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #integer

#avk47



ACCEPTED ANSWER

Score 2350


>>> str(42)
'42'

>>> int('42')
42

Links to the documentation:

str(x) converts any object x to a string by calling x.__str__(), or repr(x) if x doesn't have a __str__() method.




ANSWER 2

Score 156


Try this:

str(i)



ANSWER 3

Score 72


There is no typecast and no type coercion in Python. You have to convert your variable in an explicit way.

To convert an object into a 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.




ANSWER 4

Score 19


>>> i = 5
>>> print "Hello, world the number is " + i
TypeError: must be str, not int
>>> s = str(i)
>>> print "Hello, world the number is " + s
Hello, world the number is 5