我正在尝试为学校的一个项目构建一个基本的基于文本的天气应用程序。我是编程新手,在我的代码中遇到了错误。本质上,每当我尝试使用 f 字符串并索引字典时,我都会遇到错误。我可以不使用 f 字符串,但我想知道为什么它不起作用。
这是我遇到的错误的示例。
weather = {"day1": {"temp": "20.4", "condition" : "Partly cloudy"}, "day2": {"temp": "24.3", "condition" : "Sunny"}}
day_1_temp = weather["day1"]["temp"]
print(f"{day_1_temp}") # <-- works perfectly fine
print(f"Day 1 temperature: {weather["day1"]["temp"]}") # <-- gives an error: SyntaxError: f-string: unmatched '['
我无法通过观察来判断问题所在; “[”看起来很适合我。
试试这个
print( f"Day 1 temperature: {weather['day1']['temp']}")