Python: 如何在创建 f 字符串后对其进行评估

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

我想评估从数据库中查询到的 f 字符串。该字符串使用了我在调用该字符串之前定义的变量。

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

目前我的输出是: “我叫{name}”

但我希望它是 “我叫本”

我尝试了各种嵌套方式,包括 ''' 和 " 以及 ast.literal_eval 但不知道该怎么做。

试试这个:

print(name_phrase.format(name=name))

在创建 f-string 后对其进行评估 没有特殊功能,因此您应该使用 str.format.