", "~#").replace(">", ")").repl-6ren">
gpt4 book ai didi

python - 替换通过复制转义的字符的最pythonic方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 08:18:14 24 4
gpt4 key购买 nike

我正在寻找一个 pythonic 和高效的替代品来替代以下不言自明的代码:

term = "< << >" # turn this into "( < )"
term.replace("<<", "#~").replace(">>", "~#").replace(">", ")").replace("<", "(").replace("#~", "<").replace("~#", ">")

有什么想法吗?

最佳答案

使用正则表达式:

import re
d = {'<': '(', '>': ')'}
replaceFunc = lambda m: m.group('a') or d[m.group('b')]
pattern = r"((?P<a><|>)(?P=a)|(?P<b><|>))"
term = "< << >"

replaced = re.sub(pattern, replaceFunc, term) #returns "( < )"
根据 Niklas B 的建议

编辑

上面的正则表达式相当于匹配:

("<<" OR ">>") OR ("<" OR ">")

(?P<a><|>) #tells the re to match either "<" or ">", place the result in group 'a'
(?P=a) #tells the re to match one more of whatever was matched in the group 'a'
(?P<b><|>) #tells the re to match a sing "<" or ">" and place it in group 'b'

确实,lambda 函数 replaceFunc简单地重复这个匹配序列,但返回相关的替换字符。

re匹配“最大组优先”,所以 "<<< >"将转换为 "<( )" .

关于python - 替换通过复制转义的字符的最pythonic方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10356433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com