为什么我不能用字典格式化 f 字符串?

问题描述

dict = {"name": "Shah","birth-date": 1998,"birth_location": "New York City","major": "computer science"

print(f"{dict['name']} is a {dict['major']} who was born in {dict['birth-location]'}. He was born in {dict['birth-location]'}")


试图在 python 中使用 f 字符串打印出这个格式化的字符串,但它不起作用

解决方法

您在最后两个代码块中切换了 ] 和 ',这就是它应该的样子

并避免使用 dict 作为变量名


d = {"name": "Shah","birth-date": 1998,"birth_location": "New York City","major": "computer science"}

print(f"{d['name']} is a {d['major']} who was born in {d['birth-date']}. He was born in {d['birth_location']}")

输出: Shah is a computer science who was born in 1998. He was born in New York City