Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way of converting integers to string

>>> foo = 1
>>> type(foo)
<type 'int'>
>>> type(str(foo))
<type 'str'>
>>> type(`foo`)
<type 'str'>

Which is the more Pythonic way of converting integers to strings? I have always been using the first method but I now find the second method more readable. Is there a practical difference?

like image 227
Ayrx Avatar asked Dec 15 '22 03:12

Ayrx


1 Answers

String conversions using backticks are a shorthand notation for calling repr() on a value. For integers, the resulting output of str() and repr() happens to be the same, but it is not the same operation:

>>> example = 'bar'
>>> str(example)
'bar'
>>> repr(example)
"'bar'"
>>> `example`
"'bar'"

The backticks syntax was removed from Python 3; I wouldn't use it, as an explicit str() or repr() call is far clearer in its intent.

Note that you have more options to convert integers to strings; you can use str.format() or old style string formatting operations to interpolate an integer into a larger string:

>>> print 'Hello world! The answer is, as always, {}'.format(42)
Hello world! The answer is, as always, 42

which is much more powerful than using string concatenation.

like image 98
Martijn Pieters Avatar answered Dec 26 '22 10:12

Martijn Pieters