[英]Is there a way to unpack a dictionary into an f-string **template**?
With .format
we can unpack a dictionary into a string template.使用
.format
我们可以将字典解压成字符串模板。 That's the only thing I haven't found how to do with f-strings.这是我唯一没有找到如何处理 f-strings 的事情。 Is there a way to do it?
有没有办法做到这一点?
Eg how to do this with f-strings?例如,如何使用 f-strings 做到这一点?
template = "my values: {number} {item}"
values = dict(number=1, item='box')
print(template.format(**values))
Edit:编辑:
I thought you can have f-string templates for undefined values with something like this, but it doesn't work either:我认为您可以使用类似这样的方式为未定义的值提供 f-string 模板,但它也不起作用:
template2 = "my values: {(number := None)} {(item := None)}" # values are immutable after defining
values = dict(number=1, item='box')
# how to unpack `values` into `template2`, is it possible?
I'm aware of the longer ways to do it, what I'm looking for is only whether it's possible to use unpacking.我知道更长的方法可以做到这一点,我正在寻找的只是是否可以使用拆包。 Cheers!!
干杯!!
Not that I am aware of with f-strings, but there are string templates:我不知道 f-strings,但有字符串模板:
from string import Template
template = Template("my values: $number $item")
values = dict(number=1, item='box')
print(template.substitute(**values)) # my values: 1 box
What's wrong with these:这些有什么问题:
values = dict(number=1, item='box')
print(f"{values=}")
print(f"values= {values['number']} {values['item']}{values.get('missing')}")
which gets you:这让你:
values={'number': 1, 'item': 'box'}
values= 1 box None
Or do you want to declare your f-string before you've set up the dict and then plug in the dict?或者您想在设置字典然后插入字典之前声明您的 f 字符串? Sorry, no can do, f-strings get evaluated right away, they are not really pre-defined templates.
抱歉,不能,f 字符串会立即被评估,它们并不是真正的预定义模板。
Edit: I've worked a lot with templates, usually the %(foo)s
kind or else Jinja2 templates and have missed the capability to pass templates around, when using f-strings.编辑:我使用模板做了很多工作,通常是
%(foo)s
类型或 Jinja2 模板,并且在使用 f 字符串时错过了传递模板的能力。
This below is a hack, but it does allow doing that, after a fashion.下面是一个 hack,但它确实允许这样做,经过一段时间。 Thought of doing that a while back, never tried it though.
前阵子就想这么做了,不过没试过。
def template_1(**values):
number = values["number"]
item = values["item"]
missing = values.get("missing")
return f"values1= {number} {item} {missing}"
def template_2(**values):
return f"values2= {values['number']} {values['item']} {values.get('missing')}"
print(template_1(**values))
def do_it(t, **kwargs):
return t(**kwargs)
print(do_it(template_2,missing=3, **values))
Output Output
values1= 1 box None
values2= 1 box 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.