4
>>> 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?

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Cheers for the "shorthand notation for calling repr()" bit. Learn something new everyday.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.