在 Python 2.x 中,使用反引号从 int 对象中获取十进制字符串是可怕的吗?
因为反引号是repr()
,而不是str()
?我注意到当我回答 this 时问题。
在 Python 源代码中,它们在 Python 源代码中具有相同的功能,intobject.c
(reprfunc)int_to_decimal_string, /* tp_repr */
....
(reprfunc)int_to_decimal_string, /* tp_str */
你怎么看?
最佳答案
嗯,我不会说它“可怕”,但我觉得至少有四个原因是不对的:
str(my_number)
比用反引号包围my_number
更清楚地说明您的意图。 (请参阅 the Zen of Python 中的“可读性”)。Python 在 C 中的实现只是一种可能的实现;有 Jython、IronPython、PyPy 等等,除非在 Python 规范某处明确声明
repr()
和str()
对于整数是相同的对象,我不会依赖这种行为。Python 3.x 中没有反引号。
如果您的数字恰好太大以至于无法用
int
表示,Python 会自动将其提升为长整数,为此,repr()
和str()
不同。
看这个例子:
>>> x = 1234567890
>>> y = x ** 3
>>> `y`
'1881676371789154860897069000L'
>>> str(y)
'1881676371789154860897069000'
关于python - 在 Python 2.x 中,使用反引号从 int 对象获取十进制字符串很糟糕吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2848090/