Search code examples
pythonstringreverse

How do I reverse words in a string with Python


I am trying to reverse words of a string, but having difficulty, any assistance will be appreciated:

S = " what is my name"

def reversStr(S):
    for x in range(len(S)):
        return S[::-1]
        break

What I get now is: eman ym si tahw

However, I am trying to get: tahw is ym eman (individual words reversed)


Solution

  • def reverseStr(s):
      return ' '.join([x[::-1] for x in s.split(' ')])