首页 > 解决方案 > 什么是查找和替换格式参数的pythonic方法?

问题描述

给定一个带绑定的字符串:

input = "SELECT * FROM table WHERE col1 = %s AND col2 = %(col2_value)s"

我想转换%s?%(named)s@named这样我得到:

input = "SELECT * FROM table WHERE col1 = ? AND col2 = @col2_value"

我当前re的实现用于交换两种类型并返回绑定列表:

def _convert_bindings(query: str) -> Tuple[str, List[Union[None, str]]]:
    pos_rex = r"%s"
    named_rex = r"%\((\w+)\)s"
    bindings = [
        None if m.string == "%s" else re.search(r"%\((?P<name>\w+)\)s", m.string).group("name")
        for m in re.finditer(f"{pos_rex}|{named_rex}", query)
    ]
    sql = re.sub(pos_rex, r"?", query)
    sql = re.sub(named_rex, r"@\1", query)

    return sql, bindings

但我认为 Python 必须有一个内置的方法来查找和替换参数,因为str.format它已经有了。

那么提取%sand%(named)s并随后替换它们的最 Pythonic 方式是什么?是否有一个函数/属性可以命名为“str.params”或来自内置模块的函数 getparams?

假设没有命名参数列表的先验知识。

标签: pythonreplace

解决方案


p = re.compile("%\(([^)]*)\)s")

input = "SELECT * FROM table WHERE col1 = %s AND col2 = %(col2_value)s"

query = input.replace("%s", "?")
query = p.sub(r"@\1" , query)
  
print(query)

# SELECT * FROM table WHERE col1 = ? AND col2 = @col2_value

推荐阅读