python 字符串格式化KeyError

标签 python string formatting

我是Python初学者,在学习字符串格式化时遇到了这个问题。代码是

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

当我运行它时,错误是 KeyError:'Age'。为什么会发生这种情况?

当我使用 f 字符串时它工作得很好。

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

最佳答案

根据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!"

因此,以下内容应该按预期工作:

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

关于python 字符串格式化KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71137370/

相关文章:

python - 构造一个KMP算法要回溯多次的例子

java - 将字符串拆分为字符串数组 Java

javascript - 将日期导出为 Javascript 格式

Java StyledText,附加不同字体的文本?

python - 在 Python 中将金额转换为印度符号

python - 无法在 Python 中使用 XlsxWriter 定义输出文件

python - RE 拆分多个参数 | (或)不返回 python

python - 查找 PySpark 中给定周内的行数

python - Scrapy-splash response.css() 获取不到元素

android - Android Kotlin刷新textview