Python:'{:,}'.format()为什么这样做?

2024-09-28 20:57:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

我看过文档,但我还是不知道这到底是怎么回事?在


Tags: to函数字符串gtformatreturndef格式
3条回答

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

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

name是可选的,可以为空:

^{pr2}$

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

在本例中,format,,它指示python添加分组分隔符,如demand。 来自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声明:引入了格式说明符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.

相关问题 更多 >