我如何打印一个整数与逗号作为千分隔符?
1234567 ⟶ 1,234,567
在句点和逗号之间决定不需要特定于区域设置。
我如何打印一个整数与逗号作为千分隔符?
1234567 ⟶ 1,234,567
在句点和逗号之间决定不需要特定于区域设置。
当前回答
我得到了这个工作:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_US')
'en_US'
>>> locale.format("%d", 1255000, grouping=True)
'1,255,000'
当然,您不需要国际化支持,但它清晰、简洁,并使用了内置库。
附注:“%d”是通常的%样式格式化程序。您只能有一个格式化程序,但它可以是您在字段宽度和精度设置方面所需要的任何东西。
P.P.S.如果你不能在本地工作,我建议你修改一下Mark的答案:
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)
递归对于否定的情况是有用的,但是每个逗号一个递归对我来说似乎有点过分了。
其他回答
Python 2.5+和Python 3(仅限正int):
''.join(reversed([x + (',' if i and not i % 3 else '') for i, x in enumerate(reversed(str(1234567)))]))
我得到了这个工作:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_US')
'en_US'
>>> locale.format("%d", 1255000, grouping=True)
'1,255,000'
当然,您不需要国际化支持,但它清晰、简洁,并使用了内置库。
附注:“%d”是通常的%样式格式化程序。您只能有一个格式化程序,但它可以是您在字段宽度和精度设置方面所需要的任何东西。
P.P.S.如果你不能在本地工作,我建议你修改一下Mark的答案:
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)
递归对于否定的情况是有用的,但是每个逗号一个递归对我来说似乎有点过分了。
这个和逗号一起做钱
def format_money(money, presym='$', postsym=''):
fmt = '%0.2f' % money
dot = string.find(fmt, '.')
ret = []
if money < 0 :
ret.append('(')
p0 = 1
else :
p0 = 0
ret.append(presym)
p1 = (dot-p0) % 3 + p0
while True :
ret.append(fmt[p0:p1])
if p1 == dot : break
ret.append(',')
p0 = p1
p1 += 3
ret.append(fmt[dot:]) # decimals
ret.append(postsym)
if money < 0 : ret.append(')')
return ''.join(ret)
下面是移除不相关部分并稍微清理后的地区分组代码:
(以下仅适用于整数)
def group(number):
s = '%d' % number
groups = []
while s and s[-1].isdigit():
groups.append(s[-3:])
s = s[:-3]
return s + ','.join(reversed(groups))
>>> group(-23432432434.34)
'-23,432,432,434'
这里已经有一些很好的答案了。我只是想补充一下,以备将来参考。在python 2.7中,将有一个用于千位分隔符的格式说明符。根据python文档,它是这样工作的
>>> '{:20,.2f}'.format(f)
'18,446,744,073,709,551,616.00'
在python3.1中,你可以这样做:
>>> format(1234567, ',d')
'1,234,567'
当地unaware
'{:,}'.format(value) # For Python ≥2.7
f'{value:,}' # For Python ≥3.6
区域设置感知
import locale
locale.setlocale(locale.LC_ALL, '') # Use '' for auto, or force e.g. to 'en_US.UTF-8'
'{:n}'.format(value) # For Python ≥2.7
f'{value:n}' # For Python ≥3.6
参考
根据格式规范迷你语言,
','选项表示使用逗号作为千位分隔符。对于支持区域设置的分隔符,请使用'n'整数表示类型。