Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a string based on custom delimeter

Tags:

python

string

I have a string;

txt = "Hello$JOHN$*How*Are*$You"

I want output like:

Output: "You*$Are*How$*JOHN$Hello"

If you see closely, the character delimiters ($ and *) are NOT reversed in their sequence of occurrence. The string is reversed word-wise, but the delimiters are kept sequential.

I have tried the following:

sep=['$','*']
txt_1 = ""

for ch in txt:
    if ch in sep:
        txt_1 = txt_1+ch

I can't come up with the logic to capture the sequence of the delimiters and reverse the words of the string.

like image 258
aki2all Avatar asked Aug 14 '26 07:08

aki2all


1 Answers

One approach using regex:

import re

s = "Hello$JOHN$*How*Are*$You"

splits = re.split('([$*]+)', s)
res = ''.join(reversed(splits))

print(res)

Output

You*$Are*How$*JOHN$Hello

A (perhaps less elegant) solution (but easier to understand) is to use itertools.groupby:

from itertools import groupby

s = "Hello$JOHN$*How*Are*$You"

splits = [''.join(g) for k, g in groupby(s, key=lambda x: x in ('$', '*'))]
res = ''.join(reversed(splits))
print(res)

The idea here is to create contiguous sequence of delimiter, non-delimiter characters.

like image 112
Dani Mesejo Avatar answered Aug 16 '26 20:08

Dani Mesejo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!