首页 > 解决方案 > Python使用字典替换字符串中的变量

问题描述

那里有类似的问题,但不是我的用例。我想使用字典引用来替换字符串中的变量。在这种情况下,字符串是一个 sql 语句,但不是太相关。

带变量的 SQL {}-

qry = """SELECT
    SUM(CASE WHEN {{cols_1}} is null AND {{cols_2}} > 0 THEN 1 ELSE 0 END) AS output
    FROM mytable"""

字典 -

dict = {'cols_1': 'id', 'cols_2': 'weather'}

那么它最终会是这样 -

qry = """SELECT
    SUM(CASE WHEN id is null AND weather > 0 THEN 1 ELSE 0 END) AS output
    FROM mytable"""

我想用字典值替换 cols_1 和 cols_2。但我不知道该怎么做?

def substitute_values(qry, dict):

    if dict:
        qry = qry.replace('{{cols_1}}','{{cols_2}}'),dict[]
    
    return qry

在转动我的轮子之后,感谢任何指导。

标签: pythonstringdictionaryreplace

解决方案


使用模板。简单的:

from string import Template
qry = """SELECT SUM(CASE WHEN $cols_1 is null AND $cols_2 > 0 THEN 1 ELSE 0 END) AS output FROM mytable"""
dict = {'cols_1': 'id', 'cols_2': 'weather'}
qry = Template(qry).safe_substitute(dict)

此处的文档: https ://docs.python.org/3/library/string.html#template-strings


推荐阅读