What Does Underscore in a Python Number Mean?

Starting with Python 3.6, an underscore (_) can be used as a numeric separator between digits, to act as a visual separation:

# Python 3.6+
million = 1_000_000

print(million) # 1000000

You may use it after a decimal point as well:

# Python 3.6+
num = 1_000.101_242

print(num) # 1000.101242

Numeric separators have no semantic meaning, beyond improving readability of (long) numeric literals. In fact, numeric literals are parsed as if the underscores were absent:

# Python 3.6+
million = 1_000_000

print(million == 1000000) # True
print(million == 10_00_000) # True

When using an underscore (_) between digits, the following are considered invalid:

  • When there's more than one underscore between any two digits;
  • When a numeric literal starts or ends with an underscore;
  • When an underscore is used before or after a decimal point (or other "special positions" such as, exponent, number sign, etc.).

For example:

# SyntaxError: invalid decimal literal
100__000
# NameError: name '_100' is not defined
_100
# SyntaxError: invalid decimal literal
100_
# SyntaxError: invalid decimal literal
1_.23
# SyntaxError: invalid decimal literal
1e_23
# SyntaxError: invalid decimal literal
1_e23
# SyntaxError: invalid decimal literal
1e+_23
# SyntaxError: invalid decimal literal
1e-_23
# NameError: name '_1234' is not defined
+_1234
# NameError: name '_1234' is not defined
-_1234

You may use an underscore after base specifiers in numeric literals. For example, the following are all valid:

# Python 3.6+

0b_1011
0B_1011

0o_30_071
0O_30_071

0x_ddd_5
0X_ddd_5

# ...

You may use underscores as numeric separators with the following constructors:

  • int() (with any base);
  • float();
  • complex();
  • Decimal().

For example:

# Python 3.6+
num = int('0b_1111_0000', 2)

print(num) #=> 240

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.