Home > Software engineering >  How to replace values between two curly brackets in python?
How to replace values between two curly brackets in python?

Time:05-17

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

e.g:

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related