Skip to main content
 首页 » 编程设计

Python:如何转换随着数字计数增加而用逗号分隔的数字

2025年05月04日14telwanggs

我有一个数字:100 我在这里显示它。 但是,当我尝试将数字显示为 1000 时,我想显示为 1,000。& 以此类推,例如 1,00,000。

低于结构

数字格式为

10 10

100 100

1000 1,000

10000 10,000

100000 100000

1000000 1000000

10000000 1,00,00,000

100000000 10,00,00,000

1000000000 1,00,00,00,000

10000000000 10,00,00,00,000

以上所有我想用 python 做的事情。

我想过使用正则表达式,但不知道如何继续。

有人知道吗?

请您参考如下方法:

更新:此代码现在支持int 和float 数字!

你可以自己写一个数字到字符串的转换函数,像这样:

def special_format(n): 
    s, *d = str(n).partition(".") 
    r = ",".join([s[x-2:x] for x in range(-3, -len(s), -2)][::-1] + [s[-3:]]) 
    return "".join([r] + d) 

使用简单:

print(special_format(1)) 
print(special_format(12)) 
print(special_format(123)) 
print(special_format(1234)) 
print(special_format(12345)) 
print(special_format(123456)) 
print(special_format(12345678901234567890)) 
print(special_format(1.0)) 
print(special_format(12.34)) 
print(special_format(1234567890.1234567890)) 

上面的例子会产生这样的输出:

1 
12 
123 
1,234 
12,345 
1,23,456 
1,23,45,67,89,01,23,45,67,890 
1.0 
12.34 
1,23,45,67,890.1234567 

See this code running on ideone.com