Home > Net >  python string formatting KeyError
python string formatting KeyError

Time:02-16

I am a beginner in python language 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 exactly fine when I use Fstring.

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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