Open In App

Reverse each word in a sentence in Python

Last Updated : 20 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will explore various methods to reverse each word in a sentence. The simplest approach is by using a loop.

Using Loops

We can simply use a loop (for loop) to reverse each word in a sentence.

Python
s = "Hello World"

# Split 's' into words
words = s.split()

# Reverse each word using a loop
a = []
for word in words:
  
    # Reverse the word and add to the list
    a.append(word[::-1])

# Join the reversed words back into a single 'res'
res = " ".join(a)

print(res)

Output
olleH dlroW

Explanation:

  • s.split() breaks the sentence into words.
  • Loop through each word and reverse it using slicing (word[::-1]) and append it into list 'a'
  • Use " ".join() to join the reversed words into a single string.

To know more about reversing a string, Please refer "How to Reverse a String in Python"

Let's explore other different methods to reverse each word in a sentence:

Using List Comprehension

We can also use list comprehension to reverse each word in a sentence. This method is similar to above discussed method but this one is more concise and readable.

Python
s = "Hello World"

# Reverse each word using list comprehension
res = " ".join([word[::-1] for word in s.split()])

print(res)

Output
olleH dlroW

Explanation:

  • s.split() creates a list of words.
  • [word[::-1] for word in s.split()] reverses each word using slicing.
  • " ".join() combines the reversed words into a single string.

Using Map and Lambda

We can use map() with a lambda function to reverse each word in a sentence.

Python
s = "Hello World"
res = " ".join(map(lambda word: word[::-1], s.split()))
print(res)

Output
olleH dlroW

Explanation:

  • s.split(): Splits the sentence into a list of words.
  • map(lambda word: word[::-1], words): Applies the lambda function to reverse each word.
  • " ".join(): Combines the list of reversed words into a single string.

Next Article
Article Tags :
Practice Tags :

Similar Reads