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

How Can I Format Numbers in Python with Thousand Separators?

Linda Hamilton
Release: 2024-12-16 14:03:13
Original
447 people have browsed it

How Can I Format Numbers in Python with Thousand Separators?

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+
Copy after login

This will always use an underscore as the thousand separator. For example:

1234567  -->  1_234_567
Copy after login

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+
Copy after login

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+
Copy after login

Reference and Notes

According to the Python Format Specification Mini-Language:

  • The ',' option uses a comma for a thousands separator.
  • The 'n' specifier provides locale-aware formatting, using the appropriate thousand separator.
  • The '_' option uses an underscore for a thousands separator for floating-point and integer presentations 'd'. For integer presentations 'b', 'o', 'x', and 'X', underscores are inserted every four digits.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template