Printing Numbers with Thousand Separators
In many scenarios, it's desirable to display large numbers with commas as thousands separators for readability. Python provides several methods to achieve this, depending on your specific requirements.
Locale-Agnostic: Using Underscore
To insert commas as thousand separators regardless of the user's locale, use the _ format specifier:
print(f'{value:_}') # Python 3.6+
This will always use an underscore as the thousand separator. For example:
1234567 --> 1_234_567
English Style: Using Comma
To use a comma as the thousand separator, specific to English-language settings:
print('{:,}'.format(value)) # Python 2.7+ print(f'{value:,}') # Python 3.6+
Locale-Aware: Using 'n' Format Specifier
For locale-aware formatting, which uses the thousand separator appropriate to the user's chosen locale, use the 'n' format specifier:
import locale locale.setlocale(locale.LC_ALL, '') # Use '' for auto or specify a locale, e.g. 'en_US.UTF-8' print('{:n}'.format(value)) # Python 2.7+ print(f'{value:n}') # Python 3.6+
Reference and Notes
According to the Python Format Specification Mini-Language:
The above is the detailed content of How Can I Format Numbers in Python with Thousand Separators?. For more information, please follow other related articles on the PHP Chinese website!