I have a string in which every marked substring within <
and >
has to be reversed (the brackets don't nest). For example,
"hello <wolfrevokcats>, how <t uoy era>oday?"
should become
"hello stackoverflow, how are you today?"
My current idea is to loop over the string and find pairs of indices
where <
and >
are. Then simply slice the string and put the slices
together again with everything that was in between the markers reversed.
Is this a correct approach? Is there an obvious/better solution?
It's pretty simple with regular expressions. re.sub
takes a function as an argument to which the match object is passed.
>>> import re
>>> s = 'hello <wolfrevokcats>, how <t uoy era>oday?'
>>> re.sub('<(.*?)>', lambda m: m.group(1)[::-1], s)
'hello stackoverflow, how are you today?'
Explanation of the regex:
<(.*?)>
will match everything between <
and >
in matching group 1. To ensure that the regex engine will stop at the first >
symbol occurrence, the lazy quantifier *?
is used.
The function lambda m: m.group(1)[::-1]
that is passed to re.sub
takes the match object, extracts group 1, and reverses the string. Finally re.sub
inserts this return value.