gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:02:48 25 4
gpt4 key购买 nike

我有一个数字: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 做的事情。

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

有人知道吗?

最佳答案

更新:此代码现在支持intfloat 数字!

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

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

关于Python:如何转换随着数字计数增加而用逗号分隔的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37108757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com