
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reverse Each Word in a Sentence Using Python
The string manipulation is the common task in the python programming, especially when working with the text based data. In this article we will explore how to reverse each word in a sentence.
Generally, we reverse the entire sentence, where the both characters and the word positions are flipped, but in this task we are reversing only characters within each word while maintaining the original sequence of the words. For example if the input is "Welcome", the expected output would be "emocleW".
Using Python split() Method
The Python split() method is used to split all the words in a string by using the specified separator. This separator can be a delimiter string, a comma, full-stop. Following is the syntax of the Python split() method -
string.split(separator, maxsplit)
In this approach, we are going to split the sentence at white spaces into words by using the split() method and reversing each word using the slicing, and then joining the reversed words back into a sentence using the join() method.
Example 1
Let's look at the following example, where we are going to reverse each word in the sentence "Welcome".
def demo(a): x = a.split() y = [word[::-1] for word in x] return ' '.join(y) print(demo("Welcome"))
The output of the above program is as follows -
emocleW
Example 2
Consider another scenario, where we are going to reverse the words in the sentence "D C B A". As each word is a single character, so reversing doesn't affect them.
def demo(a): x = a.split() y = [word[::-1] for word in x] return ' '.join(y) print(demo("D C B A"))
The following is the output of the above program -
D C B A