- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
Program to reverse the position of each word of a given string in Python
Suppose we have a string of words delimited by spaces; we have to reverse the order of words.
So, if the input is like "Hello world, I love python programming", then the output will be "programming python love I world, Hello"
To solve this, we will follow these steps −
- temp := make a list of words by splitting s using blank space
- temp := reverse the list temp
- return a string by joining the elements from temp using space delimiter.
Let us see the following implementation to get better understanding −
class Solution: def solve(self, s): temp = s.split(' ') temp = list(reversed(temp)) return ' '.join(temp) ob = Solution() sentence = "Hello world, I love python programming" print(ob.solve(sentence))
"Hello world, I love python programming"
programming python love I world, Hello
- Related Articles
- Write a java program to reverse each word in string?
- Python program to reverse each word in a sentence?
- Java Program to reverse a given String with preserving the position of space.
- Write a java program reverse tOGGLE each word in the string?
- How to reverse a given string word by word instead of letters using C#?
- Program to reverse an array up to a given position in Python
- Java program to reverse each word in a sentence
- Find frequency of each word in a string in Python
- Java Program to Capitalize the first character of each word in a String
- Python program to count occurrences of a word in a string
- Golang program to capitalize first character of each word in a string
- Java program to reverse an array upto a given position
- Python program to find the character position of Kth word from a list of strings
- How to reverse a string in Python program?
- Write a Java program to capitalize each word in the string?