Sudhir Sharma
Sudhir Sharma

Reputation: 137

python string formatting KeyError

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

Upvotes: 2

Views: 536

Answers (3)

vikrant
vikrant

Reputation: 11

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

Upvotes: 0

BrokenBenchmark
BrokenBenchmark

Reputation: 19233

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

Upvotes: 2

35308
35308

Reputation: 652

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

Upvotes: 1

Related Questions