Print underscore separated integer

Viewed 1947

Since python3.6, you can use underscore to separate digits of an integer. For example

x = 1_000_000
print(x)  #1000000

This feature was added to easily read numbers with many digits and I found it very useful. But when you print the number you always get a number not separated with digits. Is there a way to print the number with its digits separated with underscore.

P.S. I want the output as integer not as string. Not "1_000_000" but 1_000_000

3 Answers

Try using this:

>>> x = 1_000_000
>>> print(f"{x:_}")
1_000_000

Another way would be to use format explicitly:

>>> x = 1_000_000
>>> print(format(x, '_d'))
1_000_000
print('{:_}'.format(x))

Output:

1_000_000

Just for fun, we could also handle this requirement using regex:

x = 1_000_000
out = re.sub(r'(\d{3})', '\\1,', str(x)[::-1])[::-1]
print(out)

This prints:

1,000,000

The idea here is to reverse the integer string, and then to replace, from left to right (in the original string), each collection of 3 digits with the same digits plus a comma separator.

Related