How to input numbers in python with comma separators?

Viewed 340

I seem to remember that there is a syntax in python to directly input numbers with comma separators (1,000,000 instead of 1000000). Googling the issue gives either results on how to:

  1. Print numbers with comma separators
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
locale.format("%d", 1255000, grouping=True)
  1. Remove commas from numbers to input into python
a = '1,000,000'
int(a.replace(',' , ''))

I don't want to do either and the plethora of results stops me from finding the information I need.

1 Answers

Instead of commas, Python allows the use of underscores.

See https://www.python.org/dev/peps/pep-0515/

grouping decimal numbers by thousands

amount = 10_000_000.0

grouping hexadecimal addresses by words

addr = 0xCAFE_F00D

grouping bits into nibbles in a binary literal

flags = 0b_0011_1111_0100_1110

same, for string conversions

flags = int('0b_1111_0000', 2)

Related