Issue
I am trying to print an integer with commas as thousands separators. For example, I want to show the number 1234567
as 1,234,567
. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way.
It does not need to be locale-specific to decide between periods and commas. I would prefer something as simple as reasonably possible.
Solution
Locale unaware
'{:,}'.format(value) # For Python ≥2.7
f'{value:,}' # For Python ≥3.6
Locale aware
import locale
locale.setlocale(locale.LC_ALL, '') # Use '' for auto, or force e.g. to 'en_US.UTF-8'
'{:n}'.format(value) # For Python ≥2.7
f'{value:n}' # For Python ≥3.6
Reference
Per Format Specification Mini-Language,
The
','
option signals the use of a comma for a thousands separator. For a locale aware separator, use the'n'
integer presentation type instead.
Answered By - Ian Schneider
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.