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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With