python:格式字符串中变量名称中的点
假设我有一本字典,字段名称中带有点,例如 {'person.name': 'Joe'}
。如果我想在 str.format
中使用它,可以吗?
我的第一直觉是,
'Name: {person.name}'.format(**{'person.name': 'Joe'})
但这只有在我的字典形状像
{'person':{'name':Joe}}
相关的 情况下才有效手册文档部分 无论如何都没有提到转义点。
(旁注:我认为这通常
def func(**kw): print(kw)
func(**{'a.b': 'Joe'})
会导致错误,但是 **
扩展的函数调用似乎可以工作,即使它们不是有效的标识符!它但在非字符串上确实会出错 o_O)
Say I've got a dictionary with dots in the name of fields, like {'person.name': 'Joe'}
. If I wanted to use this in str.format
, is it possible?
My first instinct was
'Name: {person.name}'.format(**{'person.name': 'Joe'})
but this would only work if my dict were shaped like
{'person':{'name':Joe}}
The relevant manual docs section doesn't mention anyway of escaping the dot.
(Sidenote: I thought that generally
def func(**kw): print(kw)
func(**{'a.b': 'Joe'})
would cause an error, but the **
-expanded function call seems to work even if they're not valid identifiers! It does error out on non-strings though. o_O)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
f-strings 干净地处理这个问题(我意识到它们不是在原始帖子发布时可用):
f-strings handle this cleanly (I realize they were not available at the time of the original post):
我有类似的问题,我通过继承
string.Formatter
解决了它:但是你不能使用
str.format()
因为它仍然指向旧的格式化程序,你需要像这样走I had similar issue and I solved it by inheriting from
string.Formatter
:however you can't use
str.format()
because it's still pointing to old formatter and you need to go like this解决此问题的一种方法是使用旧的
%
格式(尚未弃用):One way to work around this is to use the old
%
formatting (which has not been deprecated yet):