When working with large numbers in code, readability matters — especially when numbers have five or more digits. Just as we often group digits in threes when writing numbers in everyday life (e.g. 1,000,000), it’s helpful to do something similar in code.
In Python, you can improve the readability of numeric literals by using underscores ( _ ) to separate groups of digits. This works with integers, floating-point numbers, and complex numbers. It also applies to binary, octal, and hexadecimal integer formats.
There are no fixed rules about where underscores must be placed—you’re free to insert them wherever it makes the number easier to read.
Here are some examples:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# int with decimal digits 123_567_890 # int with hexadecimal digits 0x_49_96_02_D2 # int with octal digits 0o_11_145_401_322 # int with binary digits 0b_100_1001_1001_0110_0000_0010_1101_0010 # float 123_456.789 123_456_789e-3 # complex number 12_345 + 67_890j |
For more information about literals, see the chapter „Everything Is an Object!” in the e-book Python Knowledge Building Step by Step, specifically the subsection „How to Create Objects?”