Python: '{:,}'.format() 为何有效?

Python: '{:,}'.format() why is this working?

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

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

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

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

您可以使用 python 的格式语言,例如:

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

name 可选,可以为空:

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

format 是格式说明符。如果没有给出,通常是从给定 format(...).

的参数类型推断出来的

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

The , option signals the use of a comma for a thousands separator. For a locale aware separator, use the n integer presentation type instead.

来自documentation

Using the comma as a thousands separator:

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

说明

: 引入了格式说明符。

, 格式说明符表示使用逗号作为千位分隔符。它是在 Python 版本 2.7 和 3.1 中添加的,并且在 PEP 0378.

中有更详细的描述。

format string syntax states that : introduces the format specifier, which is defined as follows:

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

其中所有元素都是可选的,并且

The ',' option signals the use of a comma for a thousands separator. For a locale aware separator, use the 'n' integer presentation type instead.