-1

How to reverse each word in a sentence without affecting special characters in Python?

Suppose input:

" Hi, I am vip's "

Output should be like:

" iH, I ma piv's"
myke
  • 344
  • 2
  • 11

2 Answers2

1

One approach, using re.sub with a callback function:

inp = " Hi, I am vip's "
output = re.sub(r'\w+', lambda x: x.group(0)[len(x.group(0))::-1], inp)
print(inp)
print(output)

This prints:

 Hi, I am vip's 
 iH, I ma piv's 
Tim Biegeleisen
  • 451,927
  • 24
  • 239
  • 318
1

Try this:

>> strung = 'this is my string'
>> ' '.join(x[::-1] for x in strung.split())
'siht si ym gnirts'
OneCricketeer
  • 151,199
  • 17
  • 111
  • 216
CezarySzulc
  • 1,664
  • 1
  • 13
  • 26