首页 > 解决方案 > 如何将 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因为我的键是数字(除非有一个黑客来调整它,但它最终可能会比我已经拥有的更多字符)。

提前致谢。

标签: pythonpython-3.xstringdictionaryf-string

解决方案


一,你必须在你的字符串上使用不同的引号类型,否则 dict 文字中的引号会搞砸。其次,您只需在字典文字和.get():周围添加一个空格

b=f"{ {1:'a',2:'b',3:'c'}.get(i,'g') } is the letter"

添加空格的来源:this answer


推荐阅读