【问题标题】:Python: '{:,}'.format() why is this working?Python:'{:,}'.format() 为什么这样有效?
【发布时间】:2015-05-20 10:25:17
【问题描述】:

codewars 中有一个 kata,其任务是编写一个函数,该函数接受一个整数作为输入,并输出一个具有货币格式的字符串。例如123456 -> "123,456"

我有一个解决方案,但它比字符串格式的这个更难看:

def to_currency(price):
  return '{:,}'.format(price)

我已经阅读了文档,但我仍然不知道这是如何工作的?

【问题讨论】:

标签: python string string-formatting


【解决方案1】:

你可以使用python的格式语言,比如:

'{name:format}'.format(...)

name 是可选的,可以为空:

'{:format}'.format(...)

format 是一个格式说明符。如果没有给出,通常是从给format(...)的参数类型推断出来的。

在这种情况下,format,,它指示 python 添加组分隔符,就像要求的那样。 来自https://docs.python.org/2/library/string.html#formatspec

, 选项表示使用逗号作为千位分隔符。 对于区域设置感知分隔符,请使用 n 整数表示类型 而是。

【讨论】:

    【解决方案2】:

    format string syntax 声明 : 引入了格式说明符 which is defined as follows

    format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
    

    所有元素都是可选的,以及在哪里

    ,”选项表示使用逗号作为千位分隔符。对于区域设置分隔符,请改用“n”整数表示类型。

    【讨论】:

    • 我比我更喜欢你的回答:)
    【解决方案3】:

    来自documentation

    使用逗号作为千位分隔符:

    >>>
    >>> '{:,}'.format(1234567890)
    '1,234,567,890'
    

    说明

    : 引入了格式说明符。

    , 格式说明符表示使用逗号作为千位分隔符。它是在 Python 2.7 和 3.1 版本中添加的,在 PEP 0378 中有更详细的描述。

    【讨论】:

      猜你喜欢
      • 2014-12-21
      • 2012-01-05
      • 1970-01-01
      • 1970-01-01
      • 2012-05-24
      • 2020-06-28
      • 1970-01-01
      • 2012-08-21
      • 2022-01-26
      相关资源
      最近更新 更多