如何为已转换为字符串的数字添加千位分隔符?

5 投票
2 回答
1503 浏览
提问于 2025-04-17 18:43

在我的情况中(使用的是 Python 2.7),我有:

str(var)

这里的 var 是一个变量,有时候需要用千位分隔符,比如 1,500,但你可以看到它已经被转换成了字符串(为了方便拼接)。

我想把这个变量打印出来,显示成带千位分隔符的字符串。

我看过一些关于给数字添加格式的解决方案,比如:

>>> '{:20,.2}'.format(f)
'18,446,744,073,709,551,616.00'

来自 https://stackoverflow.com/a/1823189/1063287

但这些似乎只适用于数字,而不适用于已经转换成字符串的数字。

谢谢。

补充:为了提供更具体的背景,这里是我的实现场景:

print 'the cost = $' + str(var1) + '\n'
print 'the cost = $' + str(var2) + '\n'

而且我有几个 'vars'。

2 个回答

0

我很晚才看到这个问题,是因为我在寻找同样的解决方案。

使用 , 这种写法配合 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 is signed, store the sign and remove it.
    if num_str[0] == "+" or num_str[0] == "-":
        sign = num_str[0]
        num_str = num_str[1:]

    # If num_str has a decimal mark, store the fraction and remove it.
    # Note that find() will return -1 if the substring is not found.
    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]

    # Work backwards through num_str inserting a separator after every 3rd digit.
    i = len(num_str) - 3
    while i > 0:
        num_str = num_str[:i] + thousands_delimiter + num_str[i:]
        i -= 3

    # Build and return the final string.
    return sign + num_str + fraction


# Test with:

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)))


# Beginners should note that an integer or float can be converted to a string
# very easily by simply using: str(int_or_float)

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)))

希望这对你有帮助。:)

8

不要使用 str(var) 和拼接,这正是 .format() 的用处。根据 var 的类型,选择以下其中一个:

'{:,}'.format(var)    # format an integer
'{:,.2f}'.format(var) # format a decimal or float

这取决于你手头数字的类型。

>>> var = 12345678.123
>>> '{:,}'.format(int(var))  # ignore the `.123` part
'12,345,678'
>>> '{:,.2f}'.format(var)
'12,345,678.12'

撰写回答