>>> foo = 1
>>> type(foo)
<type 'int'>
>>> type(str(foo))
<type 'str'>
>>> type(`foo`)
<type 'str'>
将整数转换为字符串的Pythonic方法是哪种?我一直在使用第一种方法,但我现在发现第二种方法更具可读性。有实际的区别吗?
答案 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
比使用字符串连接更强大。