【问题标题】:Python Add Comma Into Number StringPython将逗号添加到数字字符串中
【发布时间】:2011-03-03 11:52:58
【问题描述】:

使用 Python v2,我的程序中运行着一个值 最后给出一个四舍五入到小数点后两位的数字:

像这样:

print ("Total cost is: ${:0.2f}".format(TotalAmount))

有没有办法在小数点左边每 3 位插入一个逗号值?

即:10000.00 变为 10,000.00 或 1000000.00 变为 1,000,000.00

感谢您的帮助。

【问题讨论】:

  • The Woo:在不到一个小时的时间内就同一主题提出了四个问题。你正在完成你的家庭作业。太棒了。

标签: python string


【解决方案1】:

在 Python 2.7 和 3.x 中,您可以使用格式语法:,

>>> total_amount = 10000
>>> print("{:,}".format(total_amount))
10,000
>>> print("Total cost is: ${:,.2f}".format(total_amount))
Total cost is: $10,000.00

这在PEP 378 -- Format Specifier for Thousands Separator 中有记录,在Official Docs "Using the comma as a thousands separator" 中有一个示例

【讨论】:

  • 这显然是功课。并不是说我对此有任何问题,而是:1)。它实际上并没有教给 OP 任何东西。 2)。这将 SO 变成了回答家庭作业问题的天堂。
  • @A A:99% 的 SO 用户来自谷歌。 @The Woo 是否做他的功课并不重要(尽管问题应该被标记为这样(如果是这样的话)以适当地策划答案)。它不是一个 IRC,您首先帮助个人,然后回答问题(不同的重点)。
  • 如果您使用更高版本的 Python,请参阅我对 f 字符串的回答。更简洁的实现。
【解决方案2】:

如果您使用的是 Python 3 或更高版本,以下是插入逗号的更简单方法:

第一种方式

value = -12345672
print (format (value, ',d'))

或其他方式

value = -12345672
print ('{:,}'.format(value)) 

【讨论】:

  • 这些值可能是浮点数,而不是整数,所以它是format(value, ",f")
【解决方案3】:

如果TotalAmount 代表金钱,您可以使用locale.currency。它也适用于 Python

>>> locale.setlocale(locale.LC_ALL, '')
'en_US.utf8'
>>> locale.currency(123456.789, symbol=False, grouping=True)
'123,456.79'

注意:它不适用于 C 语言环境,因此您应该在调用它之前设置一些其他语言环境。

【讨论】:

    【解决方案4】:
    '{:20,.2f}'.format(TotalAmount)
    

    【讨论】:

      【解决方案5】:

      这不是特别优雅,但也应该可以:

      a = "1000000.00"
      e = list(a.split(".")[0])
      for i in range(len(e))[::-3][1:]:
          e.insert(i+1,",")
      result = "".join(e)+"."+a.split(".")[1]
      

      【讨论】:

      • 很好的作业解决方案。
      【解决方案6】:

      一个在python2.7+或python3.1+中工作的函数

      def comma(num):
          '''Add comma to every 3rd digit. Takes int or float and
          returns string.'''
          if type(num) == int:
              return '{:,}'.format(num)
          elif type(num) == float:
              return '{:,.2f}'.format(num) # Rounds to 2 decimal places
          else:
              print("Need int or float as input to function comma()!")
      

      【讨论】:

        【解决方案7】:

        另一种很短的方法是

        value = -122212123.12
        print(f"{value:,}")
        

        【讨论】:

        • 使用 f-strings 的现代答案。
        【解决方案8】:

        上面的答案比我在我的(非家庭作业)项目中使用的代码好得多:

        def commaize(number):
            text = str(number)
            parts = text.split(".")
            ret = ""
            if len(parts) > 1:
                ret = "."
                ret += parts[1] # Apparently commas aren't used to the right of the decimal point
            # The -1 offsets to len() and 0 are because len() is 1 based but text[] is 0 based
            for i in range(len(parts[0]) - 1,-1,-1):
                # We can't just check (i % 3) because we're counting from right to left
                #  and i is counting from left to right. We can overcome this by checking
                #  len() - i, although it needs to be adjusted for the off-by-one with a -1
                # We also make sure we aren't at the far-right (len() - 1) so we don't end
                #  with a comma
                if (len(parts[0]) - i - 1) % 3 == 0 and i != len(parts[0]) - 1:
                    ret = "," + ret
                ret = parts[0][i] + ret
            return ret
        

        【讨论】:

        • “上述答案比我使用的代码好得多” - 如果现有答案更好,则无需发布质量较低的答案。此外,这篇文章已经有一个接受的答案。
        • 当时我认为它对未来的谷歌用户很有用,因为它没有其他一些答案所具有的最低 Python 版本。在对答案进行另一次审查后,我看到已经有一个。
        • +1。我喜欢这个。它提供了一个很好的细分,并让编码人员能够轻松地将这个逻辑移植到其他语言。
        【解决方案9】:

        大约 5 小时前开始学习 Python,但我想我想出了一些关于整数的东西(抱歉,无法计算浮点数)。我在高中,所以代码效率更高的可能性很大;我只是从头开始做了一些对我有意义的东西。如果有人对如何改进有任何想法并充分解释其工作原理,请告诉我!

        # Inserts comma separators
        def place_value(num):
            perm_num = num  # Stores "num" to ensure it cannot be modified
            lis_num = list(str(num))  # Makes "num" into a list of single-character strings since lists are easier to manipulate
            if len(str(perm_num)) > 3:
                index_offset = 0  # Every time a comma is added, the numbers are all shifted over one
                for index in range(len(str(perm_num))):  # Converts "perm_num" to string so len() can count the length, then uses that for a range
                    mod_index = (index + 1) % 3  # Locates every 3 index
                    neg_index = -1 * (index + 1 + index_offset)  # Calculates the index that the comma will be inserted at
                    if mod_index == 0:  # If "index" is evenly divisible by 3
                        lis_num.insert(neg_index, ",")  # Adds comma place of negative index
                        index_offset += 1  # Every time a comma is added, the index of all items in list are increased by 1 from the back
                str_num = "".join(lis_num)  # Joins list back together into string
            else:  # If the number is less than or equal to 3 digits long, don't separate with commas
                str_num = str(num)
            return str_num
        

        【讨论】:

          【解决方案10】:

          我觉得在 python 中这样使用很舒服:

          input_value=float(input())
          print("{:,}".format(input_value))
          

          【讨论】:

          • 请注意,这个问题是 9 年前回答的,您的答案已经在前 2 个答案中讨论过。
          【解决方案11】:

          最新版本的 python 使用 f-strings。所以你可以这样做:

          print("Total cost: {total_amount:,}
          

          只要 total_amount 不是字符串。否则,您需要先将其转换为数字类型,如下所示:

          print("Total cost: {Decimal(total_amount):,}
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2022-08-11
            • 1970-01-01
            • 2015-11-03
            • 1970-01-01
            • 1970-01-01
            • 2012-01-09
            • 1970-01-01
            相关资源
            最近更新 更多