2024-09-28 20:57:07 发布
网友
codewars中有一个kata,其中的任务是编写一个函数,该函数在输入中接受一个整数,并输出一个货币格式的字符串。例如123456->;"123,456"。在
123456
"123,456"
我有一个解决方案,但它比字符串格式的这个要难看得多:
def to_currency(price): return '{:,}'.format(price)
我看过文档,但我还是不知道这到底是怎么回事?在
您可以使用python的格式语言,如:
'{name:format}'.format(...)
name是可选的,可以为空:
name
format是格式说明符。如果没有给出,通常是从给format(...)的参数类型推断出来的。在
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.
n
从documentation:
Using the comma as a thousands separator:>>> >>> '{:,}'.format(1234567890) '1,234,567,890'
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.
您可以使用python的格式语言,如:
^{pr2}$name
是可选的,可以为空:format
是格式说明符。如果没有给出,通常是从给format(...)
的参数类型推断出来的。在在本例中,
format
是,
,它指示python添加分组分隔符,如demand。 来自https://docs.python.org/2/library/string.html#formatspec:从documentation:
说明
:
引入了一个格式说明符。在,
格式说明符表示使用逗号作为千位分隔符。它是在Python版本2.7和3.1中添加的,在PEP 0378中有更详细的描述。在format string syntax声明
:
引入了格式说明符which is defined as follows:所有元素都是可选的,以及
相关问题 更多 >
编程相关推荐