python - 如何将 dict 和 get 方法放在 f 字符串中?
问题描述
我有这本字典,我想将它嵌入到 f 字符串中以缩短我的代码(用于打高尔夫球的目的)。有没有办法将大括号包含在 f-string 大括号内?
# what I have:
i=2
a={1:'a',2:'b',3:'c'}.get(i,'g')
b=f'{a} is the letter'
# what I want to do but get a syntax error:
b=f'{{1:'a',2:'b',3:'c'}.get(i,'g')} is the letter'
# desired output:
'b is the letter'
我不能把{}.get
符号换掉,dict().get
因为我的键是数字(除非有一个黑客来调整它,但它最终可能会比我已经拥有的更多字符)。
提前致谢。
解决方案
一,你必须在你的字符串上使用不同的引号类型,否则 dict 文字中的引号会搞砸。其次,您只需在字典文字和.get()
:周围添加一个空格
b=f"{ {1:'a',2:'b',3:'c'}.get(i,'g') } is the letter"
添加空格的来源:this answer。
推荐阅读
- java - ulimit 已更改为 unlimit 时,无法增加 Wildfly 的“最大打开文件数”
- r - 使用具有从 R 中的本地环境获得的变量的函数(词法范围问题)
- python - 无法运行 manage.py
- python - TypeError: only size-1 arrays can be convert to Python scalars + Solution
- python - Scrapy:爬虫不爬
- python - 如何在 PyCharm 中通过元编程支持动态类型提示?
- loopbackjs - 有没有办法将文件上传与环回 3 中的特定模型相关联?
- python - 检查 argparser 是否已经定义了 arg
- javascript - 如何用数组中的空格替换“NaN”
- r - 如何在相同条件下删除整个模拟