Representing large numbers in python: the underscore separator
Recently, I learnt a simple way of representing large numbers in python. Say, I had a large number like 8736570164 I had to manually (and erratically) point my finger at the monitor on that number - look for tens, thousands, millions, etc., draw imaginary commas and come to a conclusion, as taught in school. If we cleverly had to include the commas in the number itself, python treats them as…
In Python, representing large numbers can be made easier through the use of an underscore separator. This feature was introduced in Python version 3.6. For instance, the large number 8736570164 could be represented as 8_736_570_164, which is more readable than manually counting the digits or using commas as separators.
Using underscores in numeric literals does have some rules, however. The number cannot begin or end with an underscore, and multiple underscore separators cannot be placed next to each other. For example, the following would result in an error:
- num = _314 # Error!
- num = 314 _ # Error!
- 12 __345 # Error!
Underscore separators can also be used with floats, but there cannot be an underscore directly next to the decimal point. This would also result in an error:
- num = 3 _ . 141592 # Error
- num = 3. _141592 # Error
However, the correct representation would be:
- num = 3.141_592 # Correct!
If you need to output an underscore separated number from a normal one, you can convert it to a formatted string. Python adds in the separators based on the International Number System (thousands, millions, billions, etc.). For example:
- num = 1234567890
- print(f"{num:_}") # Output: 1_234_567_890
This technique can make code easier to read, as numbers are more familiar to humans when they are written with underscores. It's a useful tool for any Python programmer, and can save time and reduce errors when working with large numbers.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.
