【问题标题】:how to add thousands separator to a number that has been converted to a string in python?如何将千位分隔符添加到已在python中转换为字符串的数字?
【发布时间】:2013-02-27 00:49:02
【问题描述】:

在我的场景中(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'

我有几个“变量”。

【问题讨论】:

    标签: python python-2.7 formatting


    【解决方案1】:

    不要使用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'
    

    【讨论】:

    • 谢谢,我的实现是print 'the cost = $' + str(var) + '\n' 所以在这种情况下我该如何应用这个逻辑?谢谢。
    • 根本不需要使用str(var),而是使用'the cost = ${:,.2f}\n'.format(var)
    • @user1063287:实际上,您的情况要简单得多。如果可以使用字符串格式,请不要使用字符串连接。
    • 非常感谢,我会采纳你的建议,在使用print 'the cost = $' + '{:20,}'.format(int(var)) + '\n'时,我会在输出值之前得到一个很大的“缩进”或“空格”
    • @user1063287:您可能想阅读formatting syntax spec;更新了答案。
    【解决方案2】:

    我在为同一件事寻找解决方案时发现的这个问题来得太晚了。

    , 表示法与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)))
    

    希望这会有所帮助。 :)

    【讨论】:

      猜你喜欢
      • 2013-10-09
      • 1970-01-01
      • 2021-11-17
      • 2010-12-19
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 2022-12-03
      • 2011-07-27
      相关资源
      最近更新 更多