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

dan*_*nny 2 python number-systems

我有一个像:100 我在这里显示的数字。但是,当我尝试将数字显示为 1000 时,又想显示为 1,000.& 等等,例如 1,00,000。

下面的结构

数字格式为

10 10

100 100

1000 1,000

10000 10,000

100000 1,00,000

1000000 10,00,000

10000000 1,00,00,000

100000000 10,00,00,000

1000000000 1,00,00,00,000

10000000000 10,00,00,00,000

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

我想过使用正则表达式,但无法找到如何继续的方法。

任何人有任何想法?

Byt*_*der 6

更新:此代码现在支持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)
Run Code Online (Sandbox Code Playgroud)

使用起来很简单:

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))
Run Code Online (Sandbox Code Playgroud)

上面的示例将导致以下输出:

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
Run Code Online (Sandbox Code Playgroud)

查看 ideone.com 上运行的此代码


Joh*_*nck 5

我认为这种分隔数字的方式是印度使用的方式。所以我认为你可以得到你想要的使用locale

import locale
locale.setlocale(locale.LC_NUMERIC, 'hi_IN')
locale.format("%d", 10000000000, grouping=True)
Run Code Online (Sandbox Code Playgroud)

在您的系统上使用的确切区域设置可能会有所不同;尝试locale -a | grep IN获取您已安装的印度语言环境列表。