python:格式字符串中变量名称中的点 [英] python: dots in the name of variable in a format string

查看:43
本文介绍了python:格式字符串中变量名称中的点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个在字段名称中带有点的字典,例如 {'person.name': 'Joe'}.如果我想在 str.format 中使用它,可以吗?

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?

我的第一直觉是

'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'})

会导致错误,但 ** 扩展的函数调用似乎可以工作,即使它们不是有效的标识符!不过,它确实 会在非字符串上出错.o_O)

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)

推荐答案

'Name: {0[person.name]}'.format({'person.name': 'Joe'})

这篇关于python:格式字符串中变量名称中的点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆