Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse marked substrings in a string

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?

like image 376
FirimaElda Avatar asked Mar 15 '26 08:03

FirimaElda


2 Answers

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.

like image 136
timgeb Avatar answered Mar 17 '26 22:03

timgeb


Or, use re.sub() and a replacing function:

>>> import re 
s = 'hello <wolfrevokcats>, how <t uoy era>oday?'
>>> re.sub(r"<(.*?)>", lambda match: match.group(1)[::-1], s)
'hello stackoverflow, how are you today?'

where .*? would match any characters any number of times in a non-greedy fashion. The parenthesis around it would help us to capture it in a group which we then refer to in the replacing function - match.group(1). [::-1] slice notation reverses a string.

like image 30
alecxe Avatar answered Mar 17 '26 22:03

alecxe