简体   繁体   English

将“十进制标记”千位分隔符添加到数字

[英]Add 'decimal-mark' thousands separators to a number

How do I format 1000000 to 1.000.000 in Python?我如何格式化10000001.000.000在Python? where the '.' '.' 在哪里is the decimal-mark thousands separator.是小数点千位分隔符。

If you want to add a thousands separator, you can write:如果要添加千位分隔符,可以这样写:

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

But it only works in Python 2.7 and above.但它仅适用于 Python 2.7 及更高版本。

Seeformat string syntax .请参阅格式字符串语法

In older versions, you can use locale.format() :在旧版本中,您可以使用locale.format()

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

the added benefit of using locale.format() is that it will use your locale's thousands separator, eg使用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'

I didn't really understand it;我真的不明白; but here is what I understand:但这是我的理解:

You want to convert 1123000 to 1,123,000.您想将 1123000 转换为 1,123,000。 You can do that by using format:您可以使用格式来做到这一点:

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

Example:例子:

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

Just extending the answer a bit here :)只是在这里稍微扩展一下答案:)

I needed to both have a thousandth separator and limit the precision of a floating point number.我需要有千分之一分隔符并限制浮点数的精度。

This can be achieved by using the following format string:这可以通过使用以下格式字符串来实现:

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

This describes the format() -specifier's mini-language:这描述了format() -specifier 的迷你语言:

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

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

An idea一个主意

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

>>> itanum(1000)
'1.000'

Using itertools can give you some more flexibility:使用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'

Drawing on the answer by Mikel, I implemented his solution like this in my matplotlib plot.借鉴 Mikel 的答案,我在我的 matplotlib 图中实现了他的解决方案。 I figured some might find it helpful:我想有些人可能会觉得它有帮助:

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

Here's only a alternative answer.这只是一个替代答案。 You can use split operator in python and through some weird logic Here's the code您可以在 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

Output输出

1.234.567.890

Strange that nobody mentioned a straightforward solution with regex:奇怪的是没有人提到正则表达式的直接解决方案:

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

Gives the following output:给出以下输出:

12.345.673.456.456.456

It also works if you want to separate the digits only before comma:如果您只想在逗号之前分隔数字,它也适用:

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

gives:给出:

123.456.734,56456456

the regex uses lookahead to check that the number of digits after a given position is divisible by 3.正则表达式使用前瞻来检查给定位置后的位数是否可以被 3 整除。

DIY solution DIY解决方案

def format_number(n):
    result = ""
    for i, digit in enumerate(reversed(str(n))):
        if i != 0 and (i % 3) == 0:
            result += ","
        result += digit
    return result[::-1]

built-in solution内置解决方案

def format_number(n):
    return "{:,}".format(n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用逗号作为千位分隔符打印数字 - How to print a number using commas as thousands separators 使用货币的通用方法,没有舍入,两个小数位和数千个分隔符 - universal method for working with currency with no rounding, two decimal places, and thousands separators 如果字符串中有逗号作为千位分隔符,如何将其转换为数字? - How to convert a string to a number if it has commas in it as thousands separators? 如何使用逗号打印数字作为Python / Django中的千位分隔符和小数位 - How to print number with commas as thousands separator and decimal places in Python/Django 在iPython中设置千位分隔符而不进行字符串格式化 - set thousands separators in iPython without string formatting 如何打印带有千位分隔符的浮点数? - How can I print a float with thousands separators? 如何在图上添加刻度线编号标签? - How to add Tick Mark Number Labels to Graph? 如何将数千个分隔符添加到已在python中转换为字符串的数字? - how to add thousands separator to a number that has been converted to a string in python? 千分和小数点的分数 - Points for thousand mark and decimal mark 如何在python中用有限的有效数字和千位分隔符格式化整数 - How to format an integer in python with limited significant figures AND thousands separators
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM