python - 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
在转动我的轮子之后,感谢任何指导。
解决方案
使用模板。简单的:
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
推荐阅读
- android - 无法获取上传到 Firebase 存储中的图像的实际下载 URL
- python - 如何在 django rest 框架序列化程序类中验证 geojson 格式
- mysql - MySQL查询获取每月数据差异
- reactjs - 我想在 swagger-ui-react 应用程序自动授权中设置 preauthorizeApiKey
- nginx - Nginx 位置重定向
- c++ - 为什么我不能从文件中读取最后一个字符串?
- c# - 打开新表单,在编译和处理 ObjectDisposedException 时不知道它的 System.Type
- android - 即使应用程序在 Android Oreo 或更高版本中被杀死,如何在后台扫描 IBeacon 以查找特定 UUID?
- c - 学生平均成绩
- javascript - 如何在vue中复制没有引用的json对象?