Skip to content Skip to sidebar Skip to footer

Print Underscore Separated Integer

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 digi

Solution 1:

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

Solution 2:

print('{:_}'.format(x))

Output:

1_000_000

Solution 3:

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.


Post a Comment for "Print Underscore Separated Integer"