我如何打印一个整数与逗号作为千分隔符?
1234567 ⟶ 1,234,567
在句点和逗号之间决定不需要特定于区域设置。
我如何打印一个整数与逗号作为千分隔符?
1234567 ⟶ 1,234,567
在句点和逗号之间决定不需要特定于区域设置。
当前回答
我很惊讶,没有人提到你可以在Python 3.6+中使用f-strings做到这一点,就像这样简单:
>>> num = 10000000
>>> print(f"{num:,}")
10,000,000
... 冒号后面的部分是格式说明符。逗号是您想要的分隔符,因此f"{num:_}"使用下划线而不是逗号。此方法只能使用“,”和“_”。
这相当于在旧版本的python 3中使用format(num, ",")。
当你第一次看到它时,它可能看起来像魔法,但它不是。它只是语言的一部分,通常需要有一个可用的快捷方式。要了解更多信息,请查看group子组件。
其他回答
我相信这一定有一个标准的库函数,但尝试自己用递归写它很有趣,所以这是我想到的:
def intToStringWithCommas(x):
if type(x) is not int and type(x) is not long:
raise TypeError("Not an integer!")
if x < 0:
return '-' + intToStringWithCommas(-x)
elif x < 1000:
return str(x)
else:
return intToStringWithCommas(x / 1000) + ',' + '%03d' % (x % 1000)
话虽如此,如果其他人确实找到了一种标准的方法,那么您应该使用它。
我得到了这个工作:
>>> 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)
递归对于否定的情况是有用的,但是每个逗号一个递归对我来说似乎有点过分了。
意大利:
>>> import locale
>>> locale.setlocale(locale.LC_ALL,"")
'Italian_Italy.1252'
>>> f"{1000:n}"
'1.000'
这是烘焙到python per PEP -> https://www.python.org/dev/peps/pep-0378/
只需使用format(1000, ',d')来显示一个带千位分隔符的整数
PEP中描述了更多的格式,请尝试一下
浮点数:
float(filter(lambda x: x!=',', '1,234.52'))
# returns 1234.52
对于整数:
int(filter(lambda x: x!=',', '1,234'))
# returns 1234