我有一个字典,我想把它嵌入到f-string中,以缩短我的代码(用于高尔夫球)。有没有办法在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'我不能用dict().get替换{}.get表示法,因为我的键是数字(除非有一种方法可以调整它,但最终它可能会比我已经有更多的字符)。
提前谢谢。
发布于 2020-11-21 07:47:52
首先,你必须在你的字符串上使用不同的引号类型,否则dict文本中的引号会把事情搞乱。其次,您只需在字典文字和.get()周围添加一个空格
b=f"{ {1:'a',2:'b',3:'c'}.get(i,'g') } is the letter"添加空格的来源:this answer。
https://stackoverflow.com/questions/64938337
复制相似问题