简体   繁体   中英

How to replace values between two curly brackets in python?

I want to replace values in strings between two curly brackets.

eg:

string  = f"""
my name is {{name}} and I'm {{age}} years old
"""

Now I want to replace name, and age by some values.

render_param = {
"name":"AHMED",
"age":20
}

so the final output should be.

my name is AHMED and I'm 20 years old.

You can work with the template render engine with:

from django.template import Template, Context

template = Template("my name is {{ name }} and I'm {{ age }} years old")
render_param = {
    'name':'AHMED',
    'age':20
}
result = template.render(Context(render_param))

If you really want that with Python, regular expressions can do it:

import re

render_param = {
"name":"AHMED",
"age":20
}

string  = f"""
my name is {{name}} and I'm {{age}} years old
"""

print(re.sub("{(.*?)}",lambda m:str(render_param[m.group(1)]),string))

results in

my name is AHMED and I'm 20 years old.

But of course if you have django anyway, use its built-in feature as shown in the other answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM