-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
  • 479
  • 3
  • 14

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
  • 502,043
  • 27
  • 286
  • 360
1

Try this:

>> strung = 'this is my string'
>> ' '.join(x[::-1] for x in strung.split())
'siht si ym gnirts'
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
CezarySzulc
  • 1,849
  • 1
  • 14
  • 30