Coding

Python 数值中的下划线是什么意思?

What's the meaning of the underscores in Python number?

JamzumSum · ·updated 2026年6月13日 · 1 min read
Number
Number Photo by @nhillier.

直入主题,看一下矛盾所在:

float(0_0)  # 0.0
float(0_0_0_0_0_0_0)  # 0.0

从其他语言转入 Python 且未系统学习过的开发者,看到这样的写法大概一时难以接受。

不过再看一个例子,或许就能理解其中的用意了:

float(1_0)  # 10.0
float(12_000) # 12000.0

Python 数值字面量中的下划线仅起视觉分隔作用,解析时等价于直接去除下划线。

This PEP proposes to extend Python's syntax and number-from-string constructors so that underscores can be used as visual separators for digit grouping purposes in integral, floating-point and complex number literals.

PEP 515,Python 3.6+。

分享
作者
JamzumSum

Open-source developer, major language: Python, C++.

Comments

Hook this up to your favourite commenting platform — Giscus, Disqus, or your own.

Continue reading