請老師解答
# 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
P相當于占位符,沒有給他賦值
2021-03-25
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)