Reverse Words in String

Write a Python function named reverse_words that takes a single string parameter. The function should return a new string where all the words in the original string are reversed but still in their original order.

Example 1:

Input: reverse_words('Hello world') 
Output: 'olleH dlrow'

Example 2:

Input: reverse_words('Python is fun') 
Output: 'nohtyP si nuf'

You can use the split method to separate the string into words, reverse each word, then join them back together.

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

© Let’s Data Science


Unlock AI & Data Science treasures. Log in!