2

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}")
2
  • 1
    print("The age of Smith is {0} and he was born in {1}{2} and his girlfriend name is {3}".format(Age,Month,Year,Gf)) Commented Feb 16, 2022 at 6:45
  • You should pass the placeholder names as well, i.e. .format(Age=Age, Month=Month, ...). Commented Feb 16, 2022 at 6:46

3 Answers 3

2

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))
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.