3
>>> foo = 1
>>> type(foo)
<type 'int'>
>>> type(str(foo))
<type 'str'>
>>> type(`foo`)
<type 'str'>
将整数转换为字符串的更多Pythonic方法是哪一种?我一直使用第一种方法,但我现在发现第二种方法更具可读性。有实际的区别吗?将整数转换为字符串的pythonic方式
>>> foo = 1
>>> type(foo)
<type 'int'>
>>> type(str(foo))
<type 'str'>
>>> type(`foo`)
<type 'str'>
将整数转换为字符串的更多Pythonic方法是哪一种?我一直使用第一种方法,但我现在发现第二种方法更具可读性。有实际的区别吗?将整数转换为字符串的pythonic方式
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
这比使用字符串连接更加强大。
为“调用repr()”位的简写符号而欢呼。每天学些新东西。 – Ayrx