我是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}")
最佳答案
根据the Python docs :
Basic usage of the str.format() method looks like this:
>>> 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))
关于python 字符串格式化KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71137370/