把整数转换成字符串的Pythonic方法

2024-03-29 11:44:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

把整数转换成字符串的更像Python的方法是什么?我一直在使用第一种方法,但现在我发现第二种方法更具可读性。有什么实际的区别吗?


Tags: 方法字符串footype整数int可读性区别
1条回答
网友
1楼 · 发布于 2024-03-29 11:44:39

String conversions using backticks是对值调用^{}的简写符号。对于整数,生成的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

这比使用字符串连接功能强大得多。

相关问题 更多 >