关于 Python f"" 和 format()

2020-06-09 11:44:12 +08:00
 5TuNan

当下有这么一个场景:

username = '川建国'
print(f"名字:{username}, 我爱{我的国}")

但是 Python 一直在报 "我的国"没有定义,并且"我的国"前后的{}还必须要带着。无奈只能使用 % 了。

请教各位大佬有没有解决方法。

2328 次点击
所在节点    程序员
11 条回复
Trim21
2020-06-09 11:48:19 +08:00
f""+""
weyou
2020-06-09 11:49:27 +08:00
print(f"名字:{username}, 我爱{{我的国}}")
Drapor
2020-06-09 11:50:10 +08:00
```
print(f"名字:{username}, 我爱{{我的国}}")
```
kokutou
2020-06-09 11:52:42 +08:00
特殊符号要转义。。
swulling
2020-06-09 11:54:11 +08:00
两个大括号括起来就可以了
yeyu123
2020-06-09 11:55:24 +08:00
f 里面 {}中是个变量. 第一个 username =川建国, 第二个 我的锅=?
zdnyp
2020-06-09 11:56:22 +08:00
我的国确实没定义啊。

username = '川建国'

myworld = '中国'

print(f"名字:{username}, 我爱{myworld}") 或者 print(f"名字:{username}, 我爱{'我的国'}")
5TuNan
2020-06-09 12:00:22 +08:00
@zdnyp 我的国 是个普通字符串。前后的{}也要保留,不做变量使用。
5TuNan
2020-06-09 12:03:25 +08:00
@weyou @swulling @Drapor 感谢三位大佬。

@kokutou 感谢,我现在就是为了寻找转义方法

@Trim21 的确是,哈哈。
no1xsyzy
2020-06-09 13:37:44 +08:00
https://www.v2ex.com/t/671782#r_8971898
…… 你可以续行混合 f-string 和一般的 string

username = '川建国'
print(f"名字:{username}, " "我爱{我的国}")
qW7bo2FbzbC0
2020-06-09 20:52:28 +08:00
```
print(f"名字:{username}, 我爱{{我的国}}")
```
c# 也是如此

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/679941

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX