Python3: Reverse words


Today I worked on this Kata – Unfortunately I forgot that there is a trick how to easily reverse whole string so I would wrote my solution shorter.

Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained.


"This is an example!" ==> "sihT si na !elpmaxe"
"double  spaces"      ==> "elbuod  secaps" test.assert_equals(reverse_words('The quick brown fox jumps over the lazy dog.'), 'ehT kciuq nworb xof spmuj revo eht yzal .god')

My Solution

def reverse_words(text):
  words = []
  for word in text.split(' '):
      word_array = list(word)
  return ' '.join(words)

Best solution

def reverse_words(str):
    return ' '.join(s[::-1] for s in str.split(' '))