4

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)
David B.
  • 371
  • 5
  • 17

2 Answers2

7

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'
falsetru
  • 357,413
  • 63
  • 732
  • 636
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
6

To do it without regular expressions, note that str.split will group consecutive whitespace when called without an explicit argument. To avoid that, specifically split on spaces. Note that you can shorten the whole function using a list comprehension:

def reverse_words(string): # don't name your own object str
    return ' '.join([word[::-1] for word in 
                     string.split(' ')])
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437