Home >Backend Development >Python Tutorial >How Can I Format Numbers with Thousands Separators in Python?

How Can I Format Numbers with Thousands Separators in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-26 18:22:10698browse

How Can I Format Numbers with Thousands Separators in Python?

Formatting Numbers with Thousands Separators

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.

Locale-Agnostic Formatting

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.

English-Style Formatting

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'

Locale-Aware Formatting

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:

  • [Format Specification Mini-Language](https://www.python.org/dev/peps/pep-0491/#format-specification-mini-language)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn