我是 Python 的初學者,遇到這個問題時正在學習字串格式化。代碼是
Age = 22
Month = "November"
Year= 1991
Gf= "julie"
print("The age of Smith is {Age} and he was born in {Month}{Year} and his girlfriend name is
{Gf}".format(Age,Month,Year,Gf))
當我運行它時,錯誤是 KeyError:'Age'。為什么會這樣?
當我使用 f 字串時它作業正常。
Age = 22
Month = "November"
Year= 1991
Gf= "julie"
print(f"The age of Smith is {Age} and he was born in {Month}{Year} and his girlfriend name is
{Gf}")
uj5u.com熱心網友回復:
根據Python 檔案:
str.format() 方法的基本用法如下所示:
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni')) We are the knights who say "Ni!"
因此,以下內容應按預期作業:
Age = 22
Month = "November"
Year= 1991
Gf= "julie"
print("The age of Smith is {} and he was born in {}{} and his girlfriend name is {}".format(Age,Month,Year,Gf))
uj5u.com熱心網友回復:
不要將變數名放在括號中,所以
Age = 22
Month = "November"
Year= 1991
Gf= "julie"
print("The age of Smith is {} and he was born in {}{} and his girlfriend name is
{}".format(Age,Month,Year,Gf))
作品
uj5u.com熱心網友回復:
在 Python 中格式化字串的新方法和改進方法
Age = 22
Month = "November"
year=1991
Gf = "juile"
print(f"The age of Smith is {Age} and he was born in {Month}{Year} and his
girlfriend name is {Gf}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/426123.html
