我看到这个问题时已经很晚了,当时我正在寻找同样的解决方案。
使用 format()
和 ,
表示法可以很好地解决问题,但会带来一些问题,因为不幸的是 ,
表示法不能应用于字符串。所以,如果你从数字的文本表示开始,那么在调用 format()
之前,你必须将它们转换为整数或浮点数。如果你需要处理整数和浮点数,并需要保留不同精度的变化水平,则 format()
代码会迅速变得相当复杂。为了处理这种情况,我最终编写了自己的代码,而没有使用 format()
。它使用最广泛使用的千位分隔符(,
)和小数点标记(.
),但显然可以非常快速地修改以适应其他地区的表示法或用于创建适用于所有语言环境的解决方案。
def separate_thousands_with_delimiter(num_str):
"""
Returns a modified version of "num_str" with thousand separators added.
e.g. "1000000" --> "1,000,000", "1234567.1234567" --> "1,234,567.1234567".
Numbers which require no thousand separators will be returned unchanged.
e.g. "123" --> "123", "0.12345" --> "0.12345", ".12345" --> ".12345".
Signed numbers (a + or - prefix) will be returned with the sign intact.
e.g. "-12345" --> "-12,345", "+123" --> "+123", "-0.1234" --> "-0.1234".
"""
decimal_mark = "."
thousands_delimiter = ","
sign = ""
fraction = ""
if num_str[0] == "+" or num_str[0] == "-":
sign = num_str[0]
num_str = num_str[1:]
dec_mark_pos = num_str.find(decimal_mark)
if dec_mark_pos >= 0:
fraction = num_str[dec_mark_pos:]
num_str = num_str[:dec_mark_pos]
i = len(num_str) - 3
while i > 0:
num_str = num_str[:i] + thousands_delimiter + num_str[i:]
i -= 3
return sign + num_str + fraction
test_nums = ["1", "10", "100", "1000", "10000", "100000", "1000000",
"-1", "+10", "-100", "+1000", "-10000", "+100000", "-1000000",
"1.0", "10.0", "100.0", "1000.0", "10000.0", "100000.0",
"1000000.0", "1.123456", "10.123456", "100.123456", "1000.123456",
"10000.123456", "100000.123456", "1000000.123456", "+1.123456",
"-10.123456", "+100.123456", "-1000.123456", "+10000.123456",
"-100000.123456", "+1000000.123456", "1234567890123456789",
"1234567890123456789.1", "-1234567890123456789.1",
"1234567890123456789.123456789", "0.1", "0.12", "0.123", "0.1234",
"-0.1", "+0.12", "-0.123", "+0.1234", ".1", ".12", ".123",
".1234", "-.1", "+.12", "-.123", "+.1234"]
for num in test_nums:
print("%s --> %s" % (num, separate_thousands_with_delimiter(num)))
test_int = 1000000
test_int_str = str(test_int)
print("%d --> %s" % (test_int, separate_thousands_with_delimiter(test_int_str)))
test_float = 1000000.1234567
test_float_str = str(test_float)
print("%f --> %s" % (test_float, separate_thousands_with_delimiter(test_float_str)))
希望这能有所帮助。 :)
print 'the cost = $' + str(var) + '\n'
,那么在这种情况下我该如何应用这个逻辑呢?谢谢。 - user1063287str(var)
,请改用'the cost = ${:,.2f}\n'.format(var)
。 - Martijn Pietersprint 'the cost = $' + '{:20,}'.format(int(var)) + '\n'
时,在输出值之前出现了大量的“缩进”或“空格”。 - user1063287