请老师解答
# Enter a code
template='Life is short,you need {P}'
ch='python'
result=template.format(P=ch)
print(result)
#这里,为什么不能直接给P赋值呢?
# Enter a code
template='Life is short,you need {P}'
P='python'
result=template.format(P)
print(result)
#这个程序为什么会出错呢?
# Enter a code
template='Life is short,you need {P}'
ch='python'
result=template.format(P=ch)
print(result)
#这里,为什么不能直接给P赋值呢?
# Enter a code
template='Life is short,you need {P}'
P='python'
result=template.format(P)
print(result)
#这个程序为什么会出错呢?
2020-09-08
template='Life is short,you need {P}'这里的P和
P='python'这里的P并不是同一个P
第一个P是给模板里的参数指定一个名字,方便调用
第二个P是变量名
result=template.format(P)这里的P是变量名
改成如下就正确(不指定参数名字):
template='Life is short,you need {}'
P='python'
result=template.format(P)
print(result)
或者改成如下(指定参数名字)
template='Life is short,you need {P}'
P='python'
result=template.format(P=P)
print(result)
这里面的result=template.format(P=P)第一个P是指参数名字,第二个P是变量名
为了避免混淆,一般要区分开来,如下:
template='Life is short,you need {x}'
P='python'
result=template.format(x=P)
print(result)
举报