0

Hi I accidentally entered the following code which I thought would result in some syntax error. But Python (3.8) executed normally and seems to concatenate the integers?

>>> 1_2
12

>>> 1.0_1.0
SyntaxError: invalid syntax

>>> 1.0_11
1.011

>>> 11_1.0
111.0

What is the _ doing exactly and when do people use that? What is the correct term for the underscore operation? It is not an operator isn't it? Since the following syntax does not work:

>>> 1_ 1
SyntaxError: invalid syntax

>>> 1 _1
SyntaxError: invalid syntax

>>> 1 _ 1
SyntaxError: invalid syntax
v.tralala
  • 1,444
  • 3
  • 18
  • 39

1 Answers1

2

It was added in PEP-515: https://www.python.org/dev/peps/pep-0515/

It's there so that large numbers are easier to read. It's not used by Python itself for anything.

For e.g.:

1000000

vs

1_000_000

It's much easier to tell that in the second case that the number is one million. The _ works just like the comma , would work in everyday numbers. (The separator couldn't be , itself since that would create a tuple)

rdas
  • 20,604
  • 6
  • 33
  • 46