我如何打印一个整数与逗号作为千分隔符?
1234567 ⟶ 1,234,567
在句点和逗号之间决定不需要特定于区域设置。
我如何打印一个整数与逗号作为千分隔符?
1234567 ⟶ 1,234,567
在句点和逗号之间决定不需要特定于区域设置。
当前回答
稍微扩展一下Ian Schneider的回答:
如果你想使用自定义千位分隔符,最简单的解决方案是:
'{:,}'.format(value).replace(',', your_custom_thousands_separator)
例子
'{:,.2f}'.format(123456789.012345).replace(',', ' ')
如果你想要像这样的德语表示,它会变得有点复杂:
('{:,.2f}'.format(123456789.012345)
.replace(',', ' ') # 'save' the thousands separators
.replace('.', ',') # dot to comma
.replace(' ', '.')) # thousand separators to dot
其他回答
你也可以使用'{: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'
我是一个Python初学者,但却是一个有经验的程序员。我有Python 3.5,所以我可以只使用逗号,但这仍然是一个有趣的编程练习。考虑无符号整数的情况。用于添加数千个分隔符的最易读的Python程序似乎是:
def add_commas(instr):
out = [instr[0]]
for i in range(1, len(instr)):
if (len(instr) - i) % 3 == 0:
out.append(',')
out.append(instr[i])
return ''.join(out)
也可以使用列表推导式:
add_commas(instr):
rng = reversed(range(1, len(instr) + (len(instr) - 1)//3 + 1))
out = [',' if j%4 == 0 else instr[-(j - j//4)] for j in rng]
return ''.join(out)
这是一个简短的,可以是一行,但你必须做一些心理体操来理解为什么它是有效的。在这两种情况下,我们得到:
for i in range(1, 11):
instr = '1234567890'[:i]
print(instr, add_commas(instr))
1 1
12 12
123 123
1234 1,234
12345 12,345
123456 123,456
1234567 1,234,567
12345678 12,345,678
123456789 123,456,789
1234567890 1,234,567,890
如果您希望程序易于理解,那么第一个版本是更明智的选择。
下面是一行正则表达式替换:
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
在低效率和不可读性方面,它是很难被击败的:
>>> 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('-,','-')
这是我处理浮点数的方法。尽管,老实说,我不确定它适用于哪个版本——我使用的是2.7:
my_number = 4385893.382939491
my_string = '{:0,.2f}'.format(my_number)
返回:4385893 .38点
更新:我最近有一个关于这种格式的问题(不能告诉你确切的原因),但能够通过删除0来修复它:
my_string = '{:,.2f}'.format(my_number)