Kat*_*Kat 4 python string string-formatting
代码组中有一个kata,其任务是编写一个函数,该函数在输入中获取整数并输出货币格式的字符串.例如123456- > "123,456".
我有一个解决方案,但它比这个字符串格式更丑:
def to_currency(price):
return '{:,}'.format(price)
Run Code Online (Sandbox Code Playgroud)
我已经阅读了文档,但我仍然不知道这是如何工作的?
您可以使用python的格式语言,如:
'{name:format}'.format(...)
Run Code Online (Sandbox Code Playgroud)
name 是可选的,可以为空:
'{:format}'.format(...)
Run Code Online (Sandbox Code Playgroud)
format是格式说明符.如果没有给出,通常从给出的参数类型推断出来format(...).
在这种情况下,formatis ,,指示python添加组分隔符,如需要.来自https://docs.python.org/2/library/string.html#formatspec:
该
,选项表示使用逗号表示千位分隔符.对于区域设置感知分隔符,请改用n整数表示类型.
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
Run Code Online (Sandbox Code Playgroud)
所有元素都是可选的,以及在哪里
'
,'选项表示使用逗号表示千位分隔符.对于区域设置感知分隔符,请改用n"整数表示形式".