[英]Python for loop within function multiple parameters
I'm currently stuck on a problem and looking for some community help.我目前遇到一个问题并寻求一些社区帮助。
I can't figure out this problem.我无法弄清楚这个问题。 Trying to replace {{ }} parameter within multiple strings with given dictionary values within a function.试图用 function 中的给定字典值替换多个字符串中的 {{ }} 参数。
Dictionary -字典 -
{'id' : 'nyc', 'weather':'sunny','id2':'bos','weather2':'snowy'}
string1 -字符串 1 -
"""
It was {{weather}} in {{id}}
"""
string2 -字符串2 -
"""
It was {{weather2}} in {{id2}}
"""
Obviously a very simplified example...显然是一个非常简化的例子......
for loop something like this - for循环是这样的-
def replace_params(qry):
for k,v in qry_params.items():
qry = qry.replace('{{'+k+'}}', v)
return qry
replace_params(string1,string2)
So output becomes所以 output 变成
"""
It was sunny in nyc
"""
I understand there are other approaches to this, but do need help with given problem using double {{ }}我知道还有其他方法可以解决此问题,但确实需要使用 double {{ }} 来解决给定问题的帮助
As mentioned in the comments, double curly braces suggest jinja2
template.如评论中所述,双花括号建议jinja2
模板。 You need yto install jinja2您需要安装jinja2
Then然后
from jinja2 import Template
data = {'id' : 'nyc', 'weather':'sunny','id2':'bos','weather2':'snowy'}
string1 = """
It was {{weather}} in {{id}}
"""
string2 = """
It was {{weather2}} in {{id2}}
"""
def render(values, *args):
return [Template(arg).render(values).strip() for arg in args]
print(render(data, string1, string2))
Output Output
['It was sunny in nyc', 'It was snowy in bos']
All that said - if you really work with template - this is not how it should be, something like this所有这一切 - 如果你真的使用模板 - 这不是应该的,就像这样
from jinja2 import Template
data = [{'id' : 'nyc', 'weather':'sunny'},{'id':'bos','weather':'snowy'}]
my_template = Template("It was {{weather}} in {{id}}")
def render(values, template):
return [my_template.render(item) for item in values]
print(render(data, my_template))
You may have the loop inside the template.您可能在模板中有循环。 But for something like this it's easier ti use single braces and f-string
or str.format()
instead of jinja tempalte.但是对于这样的事情,使用单括号和f-string
或str.format()
而不是 jinja tempalte 会更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.