首页 > 解决方案 > Python:如何在创建 f 字符串后对其进行评估

问题描述

我想评估从数据库中查询的 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但不知道该怎么做。

标签: pythonf-string

解决方案


试试这个:

print(name_phrase.format(name=name))

创建后没有用于评估an 的特殊功能,f-string因此您应该使用str.format.


推荐阅读