python:格式字符串中变量名称中的点

发布于 2024-12-12 08:37:31 字数 606 浏览 4 评论 0原文

假设我有一本字典,字段名称中带有点,例如 {'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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

紫竹語嫣☆ 2024-12-19 08:37:32

f-strings 干净地处理这个问题(我意识到它们不是在原始帖子发布时可用):

>>> x = {'person.name': 'Joe'}
>>> print(f"Name: {x['person.name']}")
Name: Joe

f-strings handle this cleanly (I realize they were not available at the time of the original post):

>>> x = {'person.name': 'Joe'}
>>> print(f"Name: {x['person.name']}")
Name: Joe
苏辞 2024-12-19 08:37:31
'Name: {0[person.name]}'.format({'person.name': 'Joe'})
'Name: {0[person.name]}'.format({'person.name': 'Joe'})
似最初 2024-12-19 08:37:31

我有类似的问题,我通过继承 string.Formatter 解决了它:

import string

class MyFormatter(string.Formatter):
    def get_field(self, field_name, args, kwargs):
        return (self.get_value(field_name, args, kwargs), field_name)

但是你不能使用 str.format() 因为它仍然指向旧的格式化程序,你需要像这样走

>>> MyFormatter().vformat("{a.b}", [], {'a.b': 'Success!'})
'Success!'

I had similar issue and I solved it by inheriting from string.Formatter:

import string

class MyFormatter(string.Formatter):
    def get_field(self, field_name, args, kwargs):
        return (self.get_value(field_name, args, kwargs), field_name)

however you can't use str.format() because it's still pointing to old formatter and you need to go like this

>>> MyFormatter().vformat("{a.b}", [], {'a.b': 'Success!'})
'Success!'
路弥 2024-12-19 08:37:31

解决此问题的一种方法是使用旧的 % 格式(尚未弃用):

>>> print 'Name: %(person.name)s' % {'person.name': 'Joe'}
Name: Joe

One way to work around this is to use the old % formatting (which has not been deprecated yet):

>>> print 'Name: %(person.name)s' % {'person.name': 'Joe'}
Name: Joe
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文