如何将数字打印为带有逗号的千位分隔符?

2024-04-25 04:22:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

它不需要特定于语言环境来决定句点和逗号。我想要尽可能简单的东西。


Tags: 方法语言环境google数字整数例子逗号
3条回答

区域设置不知道

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

区域设置感知

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.7

参考值

Format Specification Mini-Language

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

我要做的是:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_US')
'en_US'
>>> locale.format("%d", 1255000, grouping=True)
'1,255,000'

当然,您不需要国际化支持,但它清晰、简洁,并且使用内置库。

注意,“%d”是常用的%样式格式化程序。您只能有一个格式化程序,但就字段宽度和精度设置而言,它可以是您需要的任何格式。

p.p.S.如果你不能让locale工作,我建议修改马克的答案:

def intWithCommas(x):
    if type(x) not in [type(0), type(0L)]:
        raise TypeError("Parameter must be an integer.")
    if x < 0:
        return '-' + intWithCommas(-x)
    result = ''
    while x >= 1000:
        x, r = divmod(x, 1000)
        result = ",%03d%s" % (r, result)
    return "%d%s" % (x, result)

递归对于反例是有用的,但是每个逗号一次递归对我来说有点过分。

对于效率低下和不易接近的人来说,很难打败:

>>> import itertools
>>> s = '-1234567'
>>> ','.join(["%s%s%s" % (x[0], x[1] or '', x[2] or '') for x in itertools.izip_longest(s[::-1][::3], s[::-1][1::3], s[::-1][2::3])])[::-1].replace('-,','-')

相关问题 更多 >