如何用逗号打印数字作为千位分隔符?

2022-01-30 00:00:00 python number-formatting

问题描述

我试图在 Python 2.6.1 中打印一个整数,用逗号作为千位分隔符.例如,我想将数字 1234567 显示为 1,234,567.我该怎么做呢?我在谷歌上看过很多例子,但我正在寻找最简单实用的方法.

I am trying to print an integer in Python 2.6.1 with commas as thousands separators. For example, I want to show the number 1234567 as 1,234,567. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way.

在句点和逗号之间进行选择不需要特定于语言环境.我更喜欢尽可能简单的东西.

It does not need to be locale-specific to decide between periods and commas. I would prefer something as simple as reasonably possible.


解决方案

Locale unaware

'{:,}'.format(value)  # For Python ≥2.7
f'{value:,}'  # For Python ≥3.6

区域感知

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

参考

根据 格式规范迷你语言,

',' 选项表示使用逗号作为千位分隔符.对于区分区域设置的分隔符,请改用 'n' 整数表示类型.

The ',' option signals the use of a comma for a thousands separator. For a locale aware separator, use the 'n' integer presentation type instead.

相关文章