How to reverse Words in a sentence?

By Albert, 3 months ago
  • Bookmark
0

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

String
1 Answer
0

Use for loop

def reverse_words(s):
    result = "" 
    new = s.split(" ")
    for word in new: 
        word = word[::-1]+" "
        result += word
        
    return result.rstrip()      
#rstrip does not work everywhere; 
#it only works at the beginning or end of a function
 
# test case
reverse_words(s ="India is my Country")


output

"aidnI si ym yrtnuoC"


Your Answer

Webinars

Know How To Become Data Scientist.

Aug 1st (6:00 PM) 379 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More
BOT
Agent(Online)
We're Online!

Chat now for any query