Use regular expressions:
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 "( < )"
EDIT per the recommendations of Niklas B.
The above regular expression is the equivalent of matching:
("<<" 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'
Indeed, the lambda function replaceFunc
simply repeats this match sequence, but returns the relevant replacement character.
This re
matches "largest group first", so "<<< >"
will be converted to "<( )"
.