Home >Backend Development >Python Tutorial >How to Format Numbers with Thousands Separators in Python?
Formatting large numbers with thousands separators can enhance their readability. Here are several approaches to achieve this in Python:
For a universal approach, regardless of locale, you can utilize an underscore as the separator:
f'{value:_}' # For Python ≥3.6
However, this method will always employ the underscore, regardless of the current locale.
If you prefer the traditional English formatting, you can use a comma as the separator:
'{:,}'.format(value) # For Python ≥2.7 f'{value:,}' # For Python ≥3.6
To adapt to the user's locale, you can implement the following steps:
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
This method will use the appropriate separator based on the user's locale.
According to the Format Specification Mini-Language:
The above is the detailed content of How to Format Numbers with Thousands Separators in Python?. For more information, please follow other related articles on the PHP Chinese website!