>>> 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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With