Underscore separated integer in Python

Anurag M

Administrator
Staff member
Sep 1, 2023
22
0
1
XP
203
In Python, numeric separators with underscores were introduced in Python 3.6 as a way to improve the readability of large numbers by allowing you to include underscores (_) within numeric literals. These underscores are ignored by the Python interpreter, making it easier to visually separate groups of digits in long numbers. Here's how it works:

Numeric Separator Syntax: You can use underscores (_) as separators within numeric literals. You can place underscores wherever you want within the number, but there are some rules to follow:
  • Underscores cannot be placed at the beginning or end of a numeric literal.
  • Underscores cannot be used consecutively.
  • Underscores cannot be placed before or after the decimal point in floating-point numbers.
Example: Here's an example of how you can use numeric separators with underscores in Python:
Python:
large_number = 1_000_000  # Equivalent to 1000000
In the examples above, the underscores are used to visually separate groups of digits for better readability.

Output with Underscores: While you can use underscores for better readability in your code, they are ignored by the Python interpreter when parsing the numeric literals. Therefore, if you print these numbers or use them in calculations, the underscores are not included in the output:
Python:
print(large_number)  # Output: 1000000
As you can see, the output of the print statements does not include the underscores. They are only used to enhance the readability of the code.

However, there is a trick to have underscore, or any other separator displayed in the output as well. We will simply have to use Fstring in following way:
Python:
print(f"{large_number:_}")  # Output: 1_000_000
print(f"{large_number:,}")  # Output: 1,000,000