python格式字符串TypeError:并非在字符串格式化期间转换了所有参数

run*_*gel 3 python

根据“ TypeError:不是在字符串格式化期间转换的所有参数”,条目很多,但是我没有找到原因,原因如下:

print("File: %30s "%("name"))
Run Code Online (Sandbox Code Playgroud)

正在工作,但不能这样:

leng=30
print("File: %"+ str(leng) +"s "%("name"))    
Run Code Online (Sandbox Code Playgroud)

int*_*ser 6

由于操作的顺序,您的代码评估为:

"File: %" + str(leng) + ("s "%("name"))
Run Code Online (Sandbox Code Playgroud)

要解决此问题,只需在字符串中加上括号:

("File" + ...)%("name")
Run Code Online (Sandbox Code Playgroud)