Home >Backend Development >Python Tutorial >How Can I Format Numbers with Thousands Separators in Python?
When displaying large numbers, it can be helpful to include thousand separators for readability. This question examines techniques for adding commas as thousands separators when printing integers in Python.
For a locale-agnostic approach, you can use the _ character as the thousands separator. In Python 3.6 and higher, use the f' f-string syntax:
>>> f'{1234567:_}' '1_234_567'
This approach always uses _ as the separator, regardless of the user's locale settings.
To use commas as the thousand separator specifically for English-language regions, employ the following methods:
For Python 2.7 and higher:
>>> '{:,}'.format(1234567) '1,234,567'
For Python 3.6 and higher:
>>> f'{1234567:,}' '1,234,567'
To format numbers according to the user's locale settings, utilize the following code:
import locale locale.setlocale(locale.LC_ALL, '') # Use '' for auto, or force e.g. to 'en_US.UTF-8' >>> '{:n}'.format(1234567) '1,234,567' # In English-locale regions >>> '{:n}'.format(1234567) '1.234.567' # In German-locale regions
Note that f' strings with the ':n' format specifier achieve similar behavior as `'{:n}'.format()'.
References:
The above is the detailed content of How Can I Format Numbers with Thousands Separators in Python?. For more information, please follow other related articles on the PHP Chinese website!