2

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

我曾想过使用正则表达式,但不知道如何进行。

任何人有任何想法?

4

2 回答 2

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)

使用简单:

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

请参阅在 ideone.com 上运行的此代码

于 2016-05-09T06:31:20.823 回答
5

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

import locale
locale.setlocale(locale.LC_NUMERIC, 'hi_IN')
locale.format("%d", 10000000000, grouping=True)

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

于 2016-05-09T06:22:45.607 回答