-3

I want to reverse the string

Input:

I love my country! It is @beautiful

Output:

I evol ym yrtnuoc! tI si @lufituaeb
HedgeHog
  • 22,146
  • 4
  • 14
  • 36

2 Answers2

2

From each word, using regular expressions, the part without punctuation is extracted, which is reversed and replaced

import re

inp = 'I love my country! It is @beautiful'
out = []

for w in inp.split(' '):
    sw = re.search(r'[a-zA-Z]+', w)[0]
    out.append(w.replace(sw, sw[::-1]))
print(' '.join(out))

Prints:

I evol ym yrtnuoc! tI si @lufituaeb
Алексей Р
  • 7,507
  • 2
  • 7
  • 18
  • The solution assumed that punctuation is always at the boundary (or kind of), `co#untry!` --> `oc#untry!` – cards Sep 05 '22 at 21:23
2

Oneliner:

import re
text = 'I love my country! It is @beautiful'
''.join([ s[::-1] for s in re.split(r'(\W)', text)])

Results in:

'I evol ym yrtnuoc! tI si @lufituaeb'
vaizki
  • 1,678
  • 1
  • 9
  • 12
  • if punctuation not at the boundary of a word then the reversion is local (partition-like effect)l, `co#untry!` --> `oc#yrtnu!`. Also if the question doesn't provide enough information it could also be `yr#tnuoc!` – cards Sep 05 '22 at 21:20
  • Please read [answer] and [edit] your answer to contain an explanation as to why this code would actually solve the problem at hand. Always remember that you're not only solving the problem, but are also educating the OP and any future readers of this post. – Adriaan Sep 07 '22 at 09:54