This simple Python script demonstrates how to reverse the order of words in a sentence using basic string and list operations.
The script takes a string, splits it into a list of words, reverses the order of the words, and then joins them back into a single string. This is a common exercise to demonstrate string manipulation and list handling in Python.
str = "Welcome to Python Programming Language"
# Split the sentence into a list of words
words = str.split(" ")
print(words)
# Output: ['Welcome', 'to', 'Python', 'Programming', 'Language']
# Reverse the list of words
words = words[-1::-1]
print(words)
# Output: ['Language', 'Programming', 'Python', 'to', 'Welcome']
# Join the reversed list into a single string
outputstr = " ".join(words)
print(outputstr)
# Output: Language Programming Python to Welcome['Welcome', 'to', 'Python', 'Programming', 'Language']
['Language', 'Programming', 'Python', 'to', 'Welcome']
Language Programming Python to Welcome
split(" "): Splits the sentence into words based on spaces.[::-1]: Reverses the list of words.join(): Concatenates the reversed words back into a sentence.
To run this script:
- Make sure you have Python installed (version 3.x).
- Copy the code into a
.pyfile, e.g.,reverseWords.py. - Run the file using:
python reverseWords.py- Natural language processing (NLP)
- Data cleaning and formatting
- Interview questions and programming exercises