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"
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"
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
Try this:
>> strung = 'this is my string'
>> ' '.join(x[::-1] for x in strung.split())
'siht si ym gnirts'