python string formatting KeyError

Viewed 147

I am a beginner in Python and I was learning string formatting when I encountered this problem. The code is

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))

When I run it, the error is KeyError:'Age'. Why is it happening?

It works fine when I use an f-string.

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}")
3 Answers

According to 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!"

So, the following should work as intended:

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))

Don't put the variable names in the brakets so

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))

works

New and Improved Way to Format Strings in 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}")
Related