fstring和print在Python中一起使用时的奇怪行为

2024-04-26 02:37:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python3.6。我觉得下面的代码在Python中同时使用f-strings和print语句时有点奇怪

person = {"name": "Jenne", "age": 23}
print(f"Person name is {person["name"]} and age is {person["age"]}")

上述陈述导致错误

但是,当打印语句中跨越姓名和年龄的双引号替换为单引号时,它就像一种魅力。在

^{pr2}$

有人能解释一下这种行为吗?在


Tags: and代码nameageis错误语句person
1条回答
网友
1楼 · 发布于 2024-04-26 02:37:00

双引号"name"与双引号外部字符串{}冲突,也就是说,"name"的第一个双引号结束前一个字符串。你不能这样嵌套字符串。在

注意,f'Person name is...'或{}或{}都可以使用双引号。在

相关问题 更多 >