'{:,}'.format(value) # For Python ≥2.7
f'{value:,}' # For Python ≥3.7
区域设置感知
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.7
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)
>>> 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('-,','-')
区域设置不知道
区域设置感知
参考值
每Format Specification Mini-Language
我要做的是:
当然,您不需要国际化支持,但它清晰、简洁,并且使用内置库。
注意,“%d”是常用的%样式格式化程序。您只能有一个格式化程序,但就字段宽度和精度设置而言,它可以是您需要的任何格式。
p.p.S.如果你不能让
locale
工作,我建议修改马克的答案:递归对于反例是有用的,但是每个逗号一次递归对我来说有点过分。
对于效率低下和不易接近的人来说,很难打败:
相关问题 更多 >
编程相关推荐