如何将 dict 和 get 方法放入 f 字符串中?
How can you put dict and get method inside an f-string?
我有这本字典,我想将其嵌入到 f 字符串中以缩短我的代码(用于打高尔夫球)。有什么方法可以将大括号包含在 f 弦大括号内吗?
# 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 文字中的引号会把事情搞砸。其次,你只需要在字典文字周围添加一个 space 和 .get()
:
b=f"{ {1:'a',2:'b',3:'c'}.get(i,'g') } is the letter"
添加 space 的来源:this answer。
我有这本字典,我想将其嵌入到 f 字符串中以缩短我的代码(用于打高尔夫球)。有什么方法可以将大括号包含在 f 弦大括号内吗?
# 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 文字中的引号会把事情搞砸。其次,你只需要在字典文字周围添加一个 space 和 .get()
:
b=f"{ {1:'a',2:'b',3:'c'}.get(i,'g') } is the letter"
添加 space 的来源:this answer。