如何对Python整数文字使用数字分隔符? [英] How to use digit separators for Python integer literals?

查看:416
本文介绍了如何对Python整数文字使用数字分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以在Python代码中对数字进行分组以提高代码的可读性?我已经尝试过'_,它们是其中的 数字分隔符 其他语言,但无济于事.

Is there any way to group digits in a Python code to increase code legibility? I've tried ' and _ which are digit separators of some other languages, but no avail.

将左手边与右手边连接起来的怪异运算符也可以解决.

A weird operator which concatenates its left hand side with its right hand side could also work out.

推荐答案

几年后更新:Python 3.6现在支持

Update a few years later: Python 3.6 now supports PEP515, and so you can use _ for float and integer literal readability improvement.

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 .

For historical reference, you can look at the lexical analysis for strict definitions python2.7, python3.5 ...

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

For python3.6.0a2 and earlier, you should get an error message similar to:

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整数文字使用数字分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆