【问题标题】:Add 'decimal-mark' thousands separators to a number将“十进制标记”千位分隔符添加到数字
【发布时间】:2011-07-27 16:24:04
【问题描述】:

如何在 Python 中将1000000 格式化为1.000.000? '.' 在哪里是小数点千位分隔符。

【问题讨论】:

  • 请澄清您的问题。显示一些代码,提及要打印的对象的数据类型,给出示例输出。
  • 一个数字中的小数点不能超过一位。 1.000.000 应该是什么意思?你是说逗号吗?
  • @Noufal:在某些语言环境中,使用. 代替, 来分隔数千。
  • 真的吗?我没有意识到这一点。不过,我认为它们在这些语言环境中不会被称为“小数点”。
  • @NoufalIbrahim,这称为小数点,Wikipedia page 解释了哪些国家使用不同的小数点样式。

标签: python format locale number-formatting digit-separator


【解决方案1】:

如果要添加千位分隔符,可以这样写:

>>> '{0:,}'.format(1000000)
'1,000,000'

但它只适用于 Python 2.7 及更高版本。

format string syntax

在旧版本中,您可以使用locale.format()

>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'en_AU.utf8'
>>> locale.format('%d', 1000000, 1)
'1,000,000'

使用locale.format() 的额外好处是它将使用您所在地区的千位分隔符,例如

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'de_DE.utf-8')
'de_DE.utf-8'
>>> locale.format('%d', 1000000, 1)
'1.000.000'

【讨论】:

  • 如果你正在处理货币,你也可以使用 babel.numbers.format_currency 帮助器。
  • 对于浮点数,语法为{:6,.2f},其中6 是字段宽度,2 是精度。逗号的位置让我有点吃惊。
  • 您可以使用“$ locale -a”检查所有已安装的语言环境,例如默认的 Ubuntu 安装只有 en_US,因此这不是一个可行的策略。
【解决方案2】:

我真的不明白;但这是我的理解:

您想将 1123000 转换为 1,123,000。您可以通过使用格式来做到这一点:

http://docs.python.org/release/3.1.3/whatsnew/3.1.html#pep-378-format-specifier-for-thousands-separator

例子:

>>> format(1123000,',d')
'1,123,000'

【讨论】:

  • 您回答中的语言有些混乱。也许你可以改进它?
【解决方案3】:

在这里稍微扩展一下答案:)

我需要有千分之一的分隔符并限制浮点数的精度。

这可以通过使用以下格式字符串来实现:

> my_float = 123456789.123456789
> "{:0,.2f}".format(my_float)
'123,456,789.12'

这描述了format()-specifier 的迷你语言:

[[fill]align][sign][#][0][width][,][.precision][type]

来源:https://www.python.org/dev/peps/pep-0378/#current-version-of-the-mini-language

【讨论】:

  • 如果他想得到以下输出怎么办:'123.456.789,12' ?
  • @dot.Py 他可以设置适当的语言环境locale.setlocale(locale.LC_ALL, 'de_DE.utf-8') 然后使用("{:.%dn}" % (math.log10(my_float)+3)).format(my_float) 但是'n'格式字符串是'g'而不是'f'的语言环境感知等价物,因此精度字段变得混乱。
【解决方案4】:

一个想法

def itanum(x):
    return format(x,',d').replace(",",".")

>>> itanum(1000)
'1.000'

【讨论】:

  • 最简单的一种,也非常适合我的情况!替换也非常精确。
【解决方案5】:

使用itertools 可以为您提供更多灵活性:

>>> from itertools import zip_longest
>>> num = "1000000"
>>> sep = "."
>>> places = 3
>>> args = [iter(num[::-1])] * places
>>> sep.join("".join(x) for x in zip_longest(*args, fillvalue=""))[::-1]
'1.000.000'

【讨论】:

    【解决方案6】:

    根据 Mikel 的回答,我在我的 matplotlib 图中实现了这样的解决方案。我想有些人可能会觉得它有帮助:

    ax=plt.gca()
    ax.get_xaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, loc: locale.format('%d', x, 1)))
    

    【讨论】:

      【解决方案7】:

      奇怪的是,没有人提到使用正则表达式的简单解决方案:

      import re
      print(re.sub(r'(?<!^)(?=(\d{3})+$)', r'.', "12345673456456456"))
      

      给出以下输出:

      12.345.673.456.456.456
      

      如果您只想在逗号之前分隔数字,它也可以:

      re.sub(r'(?<!^)(?=(\d{3})+,)', r'.', "123456734,56456456")
      

      给予:

      123.456.734,56456456
      

      正则表达式使用前瞻来检查给定位置之后的位数是否可被 3 整除。


      2021 年更新:请仅将其用于脚本(即仅在使用后可以销毁代码的情况下)。在应用程序中使用时,这种方法将构成ReDoS

      【讨论】:

        【解决方案8】:

        这只是一个替代答案。 您可以在 python 中使用 split 运算符并通过一些奇怪的逻辑 这是代码

        i=1234567890
        s=str(i)
        str1=""
        s1=[elm for elm in s]
        if len(s1)%3==0:
            for i in range(0,len(s1)-3,3):
                str1+=s1[i]+s1[i+1]+s1[i+2]+"."
            str1+=s1[i]+s1[i+1]+s1[i+2]
        else:
            rem=len(s1)%3
            for i in range(rem):
                str1+=s1[i]
            for i in range(rem,len(s1)-1,3):
                str1+="."+s1[i]+s1[i+1]+s1[i+2]
        
        print str1
        

        输出

        1.234.567.890
        

        【讨论】:

          猜你喜欢
          • 2010-12-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-28
          • 1970-01-01
          • 1970-01-01
          • 2013-06-17
          • 1970-01-01
          相关资源
          最近更新 更多