How do I format 1000000
to 1.000.000
in Python? where the '.' is the decimal-mark thousands separator.
The character used as the thousands separatorIn the United States, this character is a comma (,). In Germany, it is a period (.). Thus one thousand and twenty-five is displayed as 1,025 in the United States and 1.025 in Germany. In Sweden, the thousands separator is a space.
Using the modern f-strings is, in my opinion, the most Pythonic solution to add commas as thousand-separators for all Python versions above 3.6: f'{1000000:,}' . The inner part within the curly brackets :, says to format the number and use commas as thousand separators.
If you want to add a thousands separator, you can write:
>>> '{0:,}'.format(1000000) '1,000,000'
But it only works in Python 2.7 and above.
See format string syntax.
In older versions, you can use locale.format():
>>> import locale >>> locale.setlocale(locale.LC_ALL, '') 'en_AU.utf8' >>> locale.format('%d', 1000000, 1) '1,000,000'
the added benefit of using locale.format()
is that it will use your locale's thousands separator, e.g.
>>> import locale >>> locale.setlocale(locale.LC_ALL, 'de_DE.utf-8') 'de_DE.utf-8' >>> locale.format('%d', 1000000, 1) '1.000.000'
I didn't really understand it; but here is what I understand:
You want to convert 1123000 to 1,123,000. You can do that by using format:
http://docs.python.org/release/3.1.3/whatsnew/3.1.html#pep-378-format-specifier-for-thousands-separator
Example:
>>> format(1123000,',d') '1,123,000'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With