請(qǐng)老師解答
# 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)
#這個(gè)程序?yàn)槭裁磿?huì)出錯(cuò)呢?
2020-09-08
P相當(dāng)于占位符,沒有給他賦值
2021-03-25
template='Life is short,you need {P}'這里的P和
P='python'這里的P并不是同一個(gè)P
第一個(gè)P是給模板里的參數(shù)指定一個(gè)名字,方便調(diào)用
第二個(gè)P是變量名
result=template.format(P)這里的P是變量名
改成如下就正確(不指定參數(shù)名字):
template='Life is short,you need {}'
P='python'
result=template.format(P)
print(result)
或者改成如下(指定參數(shù)名字)
template='Life is short,you need {P}'
P='python'
result=template.format(P=P)
print(result)
這里面的result=template.format(P=P)第一個(gè)P是指參數(shù)名字,第二個(gè)P是變量名
為了避免混淆,一般要區(qū)分開來,如下:
template='Life is short,you need {x}'
P='python'
result=template.format(x=P)
print(result)