'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}")
Solution 1:[1]
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))
Solution 2:[2]
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
Solution 3:[3]
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}")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BrokenBenchmark |
| Solution 2 | 35308 |
| Solution 3 | vikrant |
