2024-03-29 11:44:39 发布
网友
>>> foo = 1 >>> type(foo) <type 'int'> >>> type(str(foo)) <type 'str'> >>> type(`foo`) <type 'str'>
把整数转换成字符串的更像Python的方法是什么?我一直在使用第一种方法,但现在我发现第二种方法更具可读性。有什么实际的区别吗?
String conversions using backticks是对值调用^{}的简写符号。对于整数,生成的str()和repr()的输出是相同的,但它不是相同的操作:
str()
repr()
>>> example = 'bar' >>> str(example) 'bar' >>> repr(example) "'bar'" >>> `example` "'bar'"
backticks语法是removed from Python 3;我不会使用它,因为显式的str()或repr()调用的意图要清楚得多。
注意,您有更多的选项可以将整数转换为字符串;您可以使用^{}或old style string formatting operations将整数插值为更大的字符串:
>>> print 'Hello world! The answer is, as always, {}'.format(42) Hello world! The answer is, as always, 42
这比使用字符串连接功能强大得多。
String conversions using backticks是对值调用^{} 的简写符号。对于整数,生成的
str()
和repr()
的输出是相同的,但它不是相同的操作:backticks语法是removed from Python 3;我不会使用它,因为显式的
str()
或repr()
调用的意图要清楚得多。注意,您有更多的选项可以将整数转换为字符串;您可以使用^{} 或old style string formatting operations将整数插值为更大的字符串:
这比使用字符串连接功能强大得多。
相关问题 更多 >
编程相关推荐