Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse words in string - same order - including whitespace

Tags:

python

string

I am trying to reverse the letters of each words contained in a given string, keeping the same word order and also keeping the same whitespace.

So 'This is an example!' should return: 'sihT si na !elpmaxe' (note two spaces between each word).

The solution I wrote doesn't deal with this whitespace:

def reverse_words(str1):
    list1 = str1.split()
    list2 = []
    for e in list1:
        e = e[::-1]
        list2.append(e)
    return ' '.join(list2)
like image 226
David B. Avatar asked Oct 22 '25 20:10

David B.


1 Answers

If you want to preserve white space then use regex:

>>> import re
>>> s = 'This is an example!'
>>> re.sub(r'\S+', lambda m:m.group(0)[::-1], s)
'sihT si na !elpmaxe'
>>> s = 'This is an    example!'
>>> re.sub(r'\S+', lambda m:m.group(0)[::-1], s)
'sihT si na    !elpmaxe'
like image 114
Ashwini Chaudhary Avatar answered Oct 25 '25 12:10

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!