Running out of ideas where to look.
I am trying to set up a string that can be edited outside my code and stored by the user and have that string feed into an f-string inside my code.
Example:
Take the following value that is stored in database CharField:
Hello {user}! How are you?
I want to grab that and feed it into Python to treat as the content of an f-string such that:
>>> user = 'Bob'
>>> stringFromOutside = 'Hello {user}! How are you?'
>>> print(f'{stringFromOutside}')
Hello {user}! How are you?
prints "Hello Bob! How are you?"
I oversimplified for the example, because that's the core of where I'm lost.
- I have tried nesting the
{stringFromOutside}
in a second f-string, but that doesn't work. - I have also tried double
{{user}}
inside the template file, but that did not work.
Use Case in case I'm just being obtuse and doing the whole thing wrong
I have an application that I want to expose to the administrator the ability to write templates and save them in the database. The templates need to be able to pull from several different objects and all the properties of those objects, so it would be very cumbersome to try to add the substitutions manually for each possible variable that the template can include.
CodePudding user response:
user = 'Bob'
stringFromOutside = "f'Hello {user}! How are you?'"
print(eval(stringFromOutside))
You can try this
CodePudding user response:
You can use nested fstring and eval it:
user = 'Bob'
stringFromOutside = 'Hello {user}! How are you?'
print(eval(f"f'{stringFromOutside}'"))
Output:
Hello Bob! How are you?