{:02d} 在 Python 中是什么意思
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36543804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
what does {:02d} mean in Python
提问by lxdthriller
it's very hard to find information about {:}
online
I saw some code below:
很难在{:}
网上找到有关信息我在下面看到了一些代码:
def dateformat(date):
day, month, year=date.split('/')
return "{:4d}{:02d}{:02d}".format(int(year),int(month),int(day))
I kinda of know it is filling leading 0
in the format, but I don't know what do '02'
and 'd'
in {:02d}
do?
我还挺知道它是填补领先0
的格式,但我不知道该怎么做'02'
,并'd'
在{:02d}
做什么?
回答by Martijn Pieters
You are looking for the str.format()
documentation. Specifically, the 02d
part is documented in the Format Specification Mini-Language.
您正在查找str.format()
文档。具体来说,该02d
部分记录在Format Specification Mini-Language 中。
02d
formats an integer (d
) to a field of minimum width 2 (2
), with zero-padding on the left (leading 0
):
02d
将整数 ( d
)格式化为最小宽度为 2 ( 2
)的字段,左侧填充零(前导0
):
>>> 'No digits: {:02d}, 1 digit: {:02d}, 2: {:02d}, 3: {:02d}'.format(0, 7, 42, 151)
'No digits: 00, 1 digit: 07, 2: 42, 3: 151'
From the documentation:
从文档:
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
[...]
widthis a decimal integer defining the minimum field width.
When no explicit alignment is given, preceding the widthfield by a zero (
'0'
) character enables sign-aware zero-padding for numeric types. This is equivalent to a fill character of'0'
with an alignment type of'='
.[...]
Finally, the typedetermines how the data should be presented. [...]The available integer presentation types are:
[...]
'd'
Decimal Integer. Outputs the number in base 10.
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
[...]
width是定义最小字段宽度的十进制整数。
当没有给出明确的对齐方式时,在宽度字段前面加上一个零 (
'0'
) 字符为数字类型启用符号感知零填充。这相当于'0'
对齐类型为 的填充字符'='
。[...]
最后,类型决定了数据的呈现方式。[...]可用的整数表示类型有:
[...]
'd'
十进制整数。输出以 10 为底的数字。