python整数怎么表示_在Python中对整数用千分位表示

本文最后更新于2015年11月7日,已超过 1 年没有更新,如果文章内容失效,还请反馈给我,谢谢!

『即每隔三位数字加一个逗号』

搜索关键字:

python integer Thousand points representation

python Thousand points representation

参考链接:

参考解答:

I too, prefer the “simplest practical way”. For >= 2.7:

"{:,}".format(value)

#举例如下

In [1]: aint = 9876543201

In [2]: type(aint), aint

Out[2]: (int, 9876543201)

In [3]: "{:,}".format(aint)

Out[3]: '9,876,543,201'

==

I got this to work:

>>> import locale

>>> locale.setlocale(locale.LC_ALL, 'en_US')

'en_US'

>>> locale.format("%d", 1255000, grouping=True)

'1,255,000'

Sure, you don’t need internationalization support, but it’s clear, concise, and uses a built-in library.

P.S. That “%d” is the usual %-style formatter. You can have only one formatter, but it can be whatever you need in terms of field width and precision settings.

P.P.S. If you can’t get locale to work, I’d suggest a modified version of Mark’s answer:

def intWithCommas(x):

if type(x) not in [type(0), type(0L)]:

raise TypeError("Parameter must be an integer.")

if x < 0:

return '-' + intWithCommas(-x)

result = ''

while x >= 1000:

x, r = divmod(x, 1000)

result = ",%03d%s" % (r, result)

return "%d%s" % (x, result)

Recursion is useful for the negative case, but one recursion per comma seems a bit excessive to me.

==

For inefficiency and unreadability it’s hard to beat:

>>> import itertools

>>> s = '-1234567'

>>> ','.join(["%s%s%s" % (x[0], x[1] or '', x[2] or '') for x in itertools.izip_longest(s[::-1][::3], s[::-1][1::3], s[::-1][2::3])])[::-1].replace('-,','-')

=EOF=

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值