如何为 Python 整数文字使用数字分隔符?

How to use digit separators for Python integer literals?

有没有什么方法可以将 Python 代码中的数字分组以提高代码的易读性?我试过 '_,它们是 digit separators 其他一些语言,但没有用。

连接左侧和右侧的奇怪运算符也可以解决。

几年后更新:Python 3.6 现在支持 PEP515,因此您可以使用 _ 来提高浮点数和整数文字的可读性。

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 1_1000
11000
>>>

历史参考,可以看词法分析严格定义python2.7, python3.5 ...

对于 python3.6.0a2 及更早版本,您应该会收到类似于以下内容的错误消息:

Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 1_000
  File "<stdin>", line 1
    1_000
        ^
SyntaxError: invalid syntax
>>> amount = 10_000_000.0
  File "<stdin>", line 1
    amount = 10_000_000.0
                      ^
SyntaxError: invalid syntax

Python中没有这个功能,但建议以后整合

您可以在 PEP515 中看到提案。

我在 python 中看到的最接近的是 12 * 1000 * 1000,这并不理想,但如果需要 12000000 会很有用。不过请注意,虽然在 C 中,它们是等效的,因为在编译时它会将两者转换为相同的东西,python 可能不会共享此优化。

目前 Python 中没有千位分隔符,但您可以使用 locale 模块将带有此类分隔符的字符串转换为 int:

import locale
locale.setlocale(locale.LC_ALL, '')
locale.atoi("1,000,000")