我正在寻找一个 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匹配“最大组优先”,所以 "<<< >"将转换为 "<( )" .
