根据 python 中的字典键值更新字符串,其中键是部分字符串

Updating string based on dictionary key value in python where key is partial string

我有一个字符串,我想用基于特定键的值更新它。我的挑战是我字典中的一个值是部分字符串值

parameters = {"":"'name'", 
              "":"hierarchy LIKE '%|user_name|%'"}

我想用值替换 $1 和 $2 的字符串是:

query = """
  SELECT
     AS org,
   FROM
     table
   WHERE
     input ='Active'
     AND 
   GROUP BY 1, 2, 3, 4, 5, 6
"""

然后我通过下面的代码 运行 它:

for key in parameters.keys():
    query = query.replace(key, parameters[key])

将 $1 替换为 'name' 效果很好,但不能正确替换 $2。我们最终得到:

print(query)

输出:

"""
  SELECT
    'name' AS org,
   FROM
     table
   WHERE
     input ='Active'
     AND hierarchy
   GROUP BY 1, 2, 3, 4, 5, 6
"""

问题是替换 $2 时遗漏了完整的字符串。有什么建议吗?

parameters = {
    "": "'name'", 
    "": "hierarchy LIKE '%|user_name|%'",
}

str.replace

query = """
  SELECT
     AS org,
   FROM
     table
   WHERE
     input ='Active'
     AND 
   GROUP BY 1, 2, 3, 4, 5, 6
"""

for key, value in parameters.items():
    query = query.replace(key, value)

旧方法:str % (params)

query = """
  SELECT
    %s AS org,
   FROM
     table
   WHERE
     input ='Active'
     AND %s
   GROUP BY 1, 2, 3, 4, 5, 6
""" % (parameters[''], parameters[''])

更好:str.format

query = """
  SELECT
   {} AS org,
   FROM
     table
   WHERE
     input ='Active'
     AND {}
   GROUP BY 1, 2, 3, 4, 5, 6
""".format(**parameters)

新方式:f'string'

query = f"""
  SELECT
   {parameters['']} AS org,
   FROM
     table
   WHERE
     input ='Active'
     AND {parameters['']}
   GROUP BY 1, 2, 3, 4, 5, 6
"""

提示:使用 SQL 时不要使用裸字符串格式。请特别注意这些代码部分,因为 SQL 注入是众所周知的漏洞。

提示:检查您的 python 版本是否过时。 (新稳定版: 3.9), 但不要急着升级

您可以使用 re.sub:

import re
print(re.sub('$\d+', lambda x:parameters[x.group()], query))

输出

SELECT
  'name' AS org,
FROM
  table
WHERE
  input ='Active'
  AND hierarchy LIKE '%|user_name|%'
GROUP BY 1, 2, 3, 4, 5, 6