Pythonic将整数转换为字符串的方法

时间:2013-12-11 14:33:08

标签: python python-2.7

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

将整数转换为字符串的Pythonic方法是哪种?我一直在使用第一种方法,但我现在发现第二种方法更具可读性。有实际的区别吗?

1 个答案:

答案 0 :(得分:12)

String conversions using backticks是在值上调用repr()的简写表示法。对于整数,str()repr() 的结果输出是相同的,但是相同的操作:

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

反引号语法为removed from Python 3;我不会使用它,因为明确的str()repr()调用的意图要清晰得多。

请注意,您有更多选项可将整数转换为字符串;您可以使用str.format()old style string formatting operations将整数插入更大的字符串:

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

比使用字符串连接更强大。