python说明符中“10.2%”表示的含义到底是什么。


%不是转换为百分数吗?
为什么是将数字格式化为十进制。

阅读 2.6k
1 个回答

你是对的。

python 3.10 文档 格式规格

format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

可以看出 10.2%中,10对应 width.2 对应 .precision%对应type

% 在文档也明确指出是'%' 百分比。 将数字乘以 100 并显示为定点 ('f') 格式,后面带一个百分号。

最后实验证明:

>>> '{:10.2%}'.format(0.2)
'    20.00%'
>>> len('{:10.2%}'.format(0.2))
10
推荐问题