>>> foo = 1
>>> type(foo)
<type 'int'>
>>> type(str(foo))
<type 'str'>
>>> type(`foo`)
<type 'str'>
哪种方法更符合Python语言规范将整数转换为字符串?我一直在使用第一种方法,但现在我发现第二种方法更易读。有什么实际区别吗?
>>> foo = 1
>>> type(foo)
<type 'int'>
>>> type(str(foo))
<type 'str'>
>>> type(`foo`)
<type 'str'>
使用反引号进行字符串转换 是调用 repr()
来表示一个值的简写符号。对于整数而言,str()
和 repr()
的输出结果恰好相同,但它们并不是同一操作:
>>> example = 'bar'
>>> str(example)
'bar'
>>> repr(example)
"'bar'"
>>> `example`
"'bar'"
反引号语法在Python 3中已被移除; 我不建议使用它,因为明确的str()
或repr()
调用更清晰地表达了意图。
请注意,您有更多选项将整数转换为字符串; 您可以使用str.format()
或旧样式字符串格式化操作来将整数插入到较大的字符串中:
>>> print 'Hello world! The answer is, as always, {}'.format(42)
Hello world! The answer is, as always, 42