【问题标题】:What's the easiest way to add commas to an integer? [duplicate]将逗号添加到整数的最简单方法是什么? [复制]
【发布时间】:2011-04-23 23:50:39
【问题描述】:

可能重复:
How to print number with commas as thousands separators?

例如:

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

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

【问题讨论】:

    标签: python number-formatting


    【解决方案1】:

    到目前为止,还没有人提到新的',' 选项,它是在 2.7 版中添加到 Format Specification Mini-Language 的——请参阅 What's New in Python 2.7 document 中的 PEP 378: Format Specifier for Thousands Separator。它很容易使用,因为您不必乱用locale(但因此受到国际化限制,请参阅original PEP 378)。它适用于浮点数、整数和小数——以及迷你语言规范中提供的所有其他格式功能。

    示例用法:

    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'',d' 格式化类型说明符的输出不受setlocale() 的使用(或不使用)影响。但是,如果您改为使用 locale.format()locale.format_string() 函数,则 'd' 说明符会受到影响。

    【讨论】:

    • -1 不幸的是,这是损坏;它延续了语言环境模块的传统——它不能与 unicode 一起正常工作。在千位分隔符是 NO-BREAK SPACE 的语言环境(例如法语、俄语)中尝试 format(1234, u"n")。你会得到新手最喜欢的例外:UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 ...
    • @John Machin:为了记录,在我添加关于使用locale 的注释之前,大多数人都对这个答案进行了投票 - 为了大家的启发,是 i> 目前正确的为什么要以特定于语言环境的方式进行操作以处理 Unicode?谢谢。
    • (1) 点赞的时间与什么相关? (2) 没有 Python-2.X 支持的启蒙,只是一个杂牌:format(1234, "n").decode(locale.getpreferredencoding()) :-(
    • 好的,在 Python 2.x 中为此使用 locale 不适用于 Unicode 字符串。我的错(即使我从未声称它确实如此)。如果语言环境设置为法语,format(1234, "n") 会生成1 234,不会引发异常。 给您的问题:您为什么不反对或至少评论此处建议使用locale 作为主要答案的其他答案?
    • {,} 格式也适用于浮点数:例如 '{:,.2f}'.format(mydollars) 格式为美元和美分。
    【解决方案2】:

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

    还有其他解决方案here

    【讨论】:

    • +1 尽管有文档字符串,但看起来它可以处理浮点数和整数。变量名称“dollars”和“cents”的使用,除了有点过于以应用程序为中心之外,似乎支持了这一假设。非常可移植的 Python 版本,如前所述,可以回到 2.3 版,如果 enumerate() 迭代器被替换为等价的东西,则一直回到 2.0 版。
    • 对于 Python 2.4+,str(dollars)[::-1] 可以替换为更易读的reversed(str(dollars))
    • @martineau 不错的评论,我在 Google App Engine 上使用此功能,其中 Python 仅限于 2.5 版本。
    • 这家伙不适合负数:-,123,456.00
    • 在你枚举str(dollars)之前,美元不是已经是一个字符串了吗?
    【解决方案3】:

    在整数上使用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)
    

    【讨论】:

      【解决方案4】:

      locale.format()

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

      【讨论】:

      • 别忘了为可选的grouping 参数指定True 值,例如locale.format(u'%d', 1234, True)。显然locale 在处理 Unicode 方面并非完全无能为力(正如 @John Machin 在另一个答案中的 cmets 似乎暗示的那样)。
      猜你喜欢
      • 2011-01-15
      • 2011-09-28
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多