def convert(s, replacements):
for before, after in replacements.items():
s = before.join([segment.replace(before, after) for segment in s.split(before + before)])
return s
>>> convert('< << >', {'<': '(', '>': ')'})
'( < )'
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'
我会把所有的替换项放在一个列表中,然后迭代并替换:
不确定它是不是最像Python,但似乎很清楚。您甚至可以考虑接收字符列表的forloop。你知道吗
这里有一个比我第一个答案简短的方法。它将折叠字符序列上的输入拆分以删除它们,然后用替换的单个字符重新连接这些段。和以前一样,它使用字典来指定应该进行的替换。你知道吗
使用正则表达式:
根据Niklas B.的建议编辑
上述正则表达式等价于匹配:
实际上,lambda函数
replaceFunc
只是重复这个匹配序列,但返回相关的替换字符。你知道吗这个
re
匹配“最大组优先”,因此"<<< >"
将转换为"<( )"
。你知道吗相关问题 更多 >
编程相关推荐