python - 什么是查找和替换格式参数的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
它已经有了。
那么提取%s
and%(named)s
并随后替换它们的最 Pythonic 方式是什么?是否有一个函数/属性可以命名为“str.params”或来自内置模块的函数 getparams?
假设没有命名参数列表的先验知识。
解决方案
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
推荐阅读
- python-3.x - 如何在 chrome 中为 selenium 设置假音频路径?
- javascript - 在哪些情况下您会关心浏览器选择的方向?
- javascript - 用点后 2 位小数分割字符串
- sparql - 出现次数 SPARQL
- haskell - Profunctor 的哪些属性不能进入 Haskell/PureScript?
- html - 将“list-group”放在右侧,而“cards”在左侧,Bootstrap
- makefile - 更改项目目录后Makefile不起作用
- c++ - 如何解决 OJ 上的“运行时错误”
- ruby-on-rails - Bundler 尝试更新 rails 但其版本保持不变
- r - 使用 tidyverse 和 base R 删除列 - 区别