Search code examples
pythonf-string

Python: How can I evaluate an f-string after it is created


I'd like to evaluate an f-string that I have queried from a database. This string uses a variable I have defined before calling the string.

def get_name():
    name = "Ben"

    # from database (the value within the text field I call "name_question" in postgresql says: "My name is {name}")
    name_phrase = DB.objects.get(phrases=name_question)
    
    print(f'{name_phrase}')

At the moment my output is: "My name is {name}"

But I would like it to be "My name is Ben"

I have tried various ways of nesting, with ''' and " as well as ast.literal_eval but cannot figure out how to do it.


Solution

  • Try this one:

    print(name_phrase.format(name=name))
    

    There is no special function for evaluating an f-string after it is created so you should use str.format.