38

可能重复:
如何用逗号打印数字作为千位分隔符?

例如:

>> print numberFormat(1234)
>> 1,234

或者 Python 中是否有一个内置函数可以做到这一点?

4

4 回答 4

102

到目前为止,没有人提到','在 2.7 版中添加到格式规范迷你语言的新选项——请参阅Python 2.7 文档中的PEP 378:千位分隔符的格式说明符。它很容易使用,因为您不必乱搞(但由于国际化而受到限制,请参阅原始 PEP 378)。它适用于浮点数、整数和小数——以及迷你语言规范中提供的所有其他格式功能。locale

示例用法:

print format(1234, ",d")    # -> 1,234
print "{:,d}".format(1234)  # -> 1,234
print(f'{1234:,d}')         # -> 1,234 (Python 3.6+)

注意:虽然这个新功能确实很方便,但实际上使用该模块并没有那么难locale,正如其他几个人所建议的那样。其优点是,在输出数字、日期和时间等内容时,可以使数字输出自动遵循各个国家/地区使用的适当的千位(和其他)分隔符约定。无需学习大量语言和国家/地区代码,即可将计算机中的默认设置生效也很容易。您需要做的就是:

import locale
locale.setlocale(locale.LC_ALL, '')  # empty string for platform's default settings

之后,您可以使用通用'n'类型代码来输出数字(整数和浮点数)。在我所在的位置,逗号用作千位分隔符,因此在如上所示设置语言环境后,会发生以下情况:

print format(1234, "n")    # -> 1,234
print "{:n}".format(1234)  # -> 1,234

世界上大部分地区为此使用句点而不是逗号,因此在许多位置设置默认语言环境(或在setlocale()调用中明确指定此类区域的代码)会产生以下结果:

print format(1234, "n")    # -> 1.234
print "{:n}".format(1234)  # -> 1.234

基于'd'or',d'格式化类型说明符的输出不受使用(或不使用)的影响setlocale()。但是,如果您改为使用or函数,则'd'说明符会受到影响。locale.format()locale.format_string()

于 2010-10-11T20:57:05.630 回答
13

locale.format()

不要忘记首先适当地设置语言环境。

于 2010-10-11T19:53:11.430 回答
12

从webpy 中 剥离utils.py

def commify(n):
    """
    Add commas to an integer `n`.

        >>> commify(1)
        '1'
        >>> commify(123)
        '123'
        >>> commify(1234)
        '1,234'
        >>> commify(1234567890)
        '1,234,567,890'
        >>> commify(123.0)
        '123.0'
        >>> commify(1234.5)
        '1,234.5'
        >>> commify(1234.56789)
        '1,234.56789'
        >>> commify('%.2f' % 1234.5)
        '1,234.50'
        >>> commify(None)
        >>>

    """
    if n is None: return None
    n = str(n)
    if '.' in n:
        dollars, cents = n.split('.')
    else:
        dollars, cents = n, None

    r = []
    for i, c in enumerate(str(dollars)[::-1]):
        if i and (not (i % 3)):
            r.insert(0, ',')
        r.insert(0, c)
    out = ''.join(r)
    if cents:
        out += '.' + cents
    return out

这里还有其他解决方案。

于 2010-10-11T19:56:55.203 回答
5

在整数上使用locale.format(),但要注意环境中的当前语言环境。某些环境可能没有此设置或设置为不会给您带来 commafied 结果的东西。

这是我必须编写的一些代码来处理这个确切的问题。它会根据您的平台自动为您设置语言环境:

try:
    locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') #use locale.format for commafication
except locale.Error:
    locale.setlocale(locale.LC_ALL, '') #set to default locale (works on windows)

score = locale.format('%d', player['score'], True)
于 2010-10-11T20:17:11.047 回答