Python tip 13: formatting numbers with underscore separation
For readability purposes, you can use underscores while declaring large numbers. For example:
>>> 1_000_000_000
1000000000
>>> 0b1000_1111
143
Did you know that you can also format numbers with underscore separation?
>>> n = 14310023
# underscore separation
>>> f'{n:_}'
'14_310_023'
# you can also use comma separation for integers
>>> f'{n:,}'
'14,310,023'
Here are some examples for displaying numbers in binary, octal and hexadecimal formats:
>>> n = 14310023
>>> f'{n:_b}'
'1101_1010_0101_1010_1000_0111'
>>> f'{n:#_b}'
'0b1101_1010_0101_1010_1000_0111'
>>> f'{n:#_x}'
'0xda_5a87'
>>> f'{n:#_o}'
'0o6645_5207'
And here's an example with zero filling:
>>> for n in (3, 20, 28):
... print(f'{n:09_b}')
...
0000_0011
0001_0100
0001_1100
See docs.python: Formatted string literals for documentation and other examples.
Video demo:
See also my 100 Page Python Intro ebook.