我如何打印一个整数与逗号作为千分隔符?
1234567 ⟶ 1,234,567
在句点和逗号之间决定不需要特定于区域设置。
我如何打印一个整数与逗号作为千分隔符?
1234567 ⟶ 1,234,567
在句点和逗号之间决定不需要特定于区域设置。
当前回答
我相信这一定有一个标准的库函数,但尝试自己用递归写它很有趣,所以这是我想到的:
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)
话虽如此,如果其他人确实找到了一种标准的方法,那么您应该使用它。
其他回答
Python 2.5+和Python 3(仅限正int):
''.join(reversed([x + (',' if i and not i % 3 else '') for i, x in enumerate(reversed(str(1234567)))]))
你也可以使用'{:n}'。区域设置表示的格式(值)。我认为这是最简单的现场解决方案。
有关更多信息,请在Python DOC中搜索数千个。
对于货币,可以使用locale。货币,设置标志分组:
Code
import locale
locale.setlocale( locale.LC_ALL, '' )
locale.currency( 1234567.89, grouping = True )
输出
'Portuguese_Brazil.1252'
'R$ 1.234.567,89'
通用解决方案
我在以前投票最多的答案中发现了点分隔符的一些问题。我已经设计了一个通用的解决方案,您可以使用任何您想要作为千个分隔符,而无需修改区域设置。我知道这不是最优雅的解决方案,但它完成了工作。请随意改进它!
def format_integer(number, thousand_separator='.'):
def reverse(string):
string = "".join(reversed(string))
return string
s = reverse(str(number))
count = 0
result = ''
for char in s:
count = count + 1
if count % 3 == 0:
if len(s) == count:
result = char + result
else:
result = thousand_separator + char + result
else:
result = char + result
return result
print(format_integer(50))
# 50
print(format_integer(500))
# 500
print(format_integer(50000))
# 50.000
print(format_integer(50000000))
# 50.000.000
在浮点数中同时使用分隔符和小数: (在这个例子中,小数点后两位)
large_number = 4545454.26262666
print(f"Formatted: {large_number:,.2f}")
结果: 格式:4545454点
下面是一行正则表达式替换:
re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%d" % val)
仅适用于积分输出:
import re
val = 1234567890
re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%d" % val)
# Returns: '1,234,567,890'
val = 1234567890.1234567890
# Returns: '1,234,567,890'
或者对于小于4位的浮点数,将格式说明符更改为%.3f:
re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%.3f" % val)
# Returns: '1,234,567,890.123'
注意:不能正确工作与超过三个十进制数字,因为它将尝试分组小数部分:
re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%.5f" % val)
# Returns: '1,234,567,890.12,346'
它是如何工作的
让我们来分析一下:
re.sub(pattern, repl, string)
pattern = \
"(\d) # Find one digit...
(?= # that is followed by...
(\d{3})+ # one or more groups of three digits...
(?!\d) # which are not followed by any more digits.
)",
repl = \
r"\1,", # Replace that one digit by itself, followed by a comma,
# and continue looking for more matches later in the string.
# (re.sub() replaces all matches it finds in the input)
string = \
"%d" % val # Format the string as a decimal to begin with