Add 'decimal-mark' thousands separators to

2019-01-04 02:39发布

How do I format 1000000 to 1.000.000 in Python? where the '.' is the decimal-mark thousands separator.

8条回答
太酷不给撩
2楼-- · 2019-01-04 03:04

I didn't really understand it; but here is what I understand:

You want to convert 1123000 to 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

Example:

>>> format(1123000,',d')
'1,123,000'
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-04 03:10

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:

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

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

查看更多
4楼-- · 2019-01-04 03:11

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.

查看更多
Melony?
5楼-- · 2019-01-04 03:13

Drawing on the answer by Mikel, I implemented his solution like this in my matplotlib plot. 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)))
查看更多
家丑人穷心不美
6楼-- · 2019-01-04 03:21

Here's only a alternative answer. You can use split operator in python and through some weird logic Here's the code

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
查看更多
干净又极端
7楼-- · 2019-01-04 03:23

An idea

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

>>> itanum(1000)
'1.000'
查看更多
登录 后发表回答