Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/kubernetes/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么f";{11:2d}";不可以填充到2个字符?_Python_Format String_F String - Fatal编程技术网

Python 为什么f";{11:2d}";不可以填充到2个字符?

Python 为什么f";{11:2d}";不可以填充到2个字符?,python,format-string,f-string,Python,Format String,F String,我正在使用ipython7.0.1和python3.6.9 我想用格式字符串迷你语言右对齐数字。我使用1和11作为1位和2位数字的示例,我希望将其填充为总共2个字符 对于零填充,一切都按预期工作,是可选的,因为它是默认值: In [0]: print(f"{1:02d}\n{11:02d}\n{1:0>2d}\n{11:0>2d}") 01 11 01 11 但当我想用空格填充时,只要我不使用空格,使

我正在使用
ipython7.0.1
python3.6.9

我想用格式字符串迷你语言右对齐数字。我使用
1
11
作为1位和2位数字的示例,我希望将其填充为总共2个字符

对于零填充,一切都按预期工作,
是可选的,因为它是默认值:

In [0]: print(f"{1:02d}\n{11:02d}\n{1:0>2d}\n{11:0>2d}")                                         
01
11
01
11
但当我想用空格填充时,只要我不使用空格,使其默认为空格,它也可以工作:

In [1]: print(f"{1:2d}\n{11:2d}\n{1:>2d}\n{11:>2d}")                                             
 1
11
 1
11
但是如果我显式地键入空格,我会对结果感到惊讶:

In [2]: print(f"{1: 2d}\n{11: 2d}\n{1: >2d}\n{11: >2d}")                                         
 1
 11
 1
11

为什么会这样?

所有这些都在文档中

格式规格::=[[fill]align][sign]

如果指定了有效的对齐值,则该值前面可以有填充字符

由于
填充
符号
都可以是
空格
,因此
空格
作为
填充
必须后跟
对齐

下面是Python如何解释您的最后一行:

f"{1: 2d}"    #interpreted as sign therefore (accidentally) same effect  -> " 1"
f"{11: 2d}"   #interpreted as sign therefore a leading space is inserted -> " 11"
f"{1: >2d}"   #align is present, pad with ' '                            -> " 1"
f"{11: >2d}"  #align is present, pad with ' ' but number long enough     -> "11"