Python: Reverse Words in String

1. Introduction

Reversing the words in a string is a common programming task that tests one's knowledge of string manipulations. Given a sentence, we want to reverse the order of its words while keeping the sequence of characters in each word the same. For example, given "Python is fun", the output should be "fun is Python".

2. Program Overview

1. The program will prompt the user to enter a string.

2. It will then split the string into words.

3. The words will be reversed, and then combined back to form the final reversed string.

3. Code Program

# Python program to reverse words in a string

# Taking input from the user
input_string = input("Enter a sentence: ")

# Splitting the string into words
words = input_string.split()

# Reversing the list of words
reversed_words = words[::-1]

# Joining the words to form the reversed string
reversed_string = ' '.join(reversed_words)

print("Reversed Sentence:", reversed_string)

Output:

Enter a sentence: Learning Python is enjoyable
Reversed Sentence: enjoyable is Python Learning

4. Step By Step Explanation

1. We begin by taking a sentence (or any string) from the user.

2. The split() method is used to split the string into a list of words. By default, this method splits the string wherever it finds a space.

3. To reverse the list of words, we use Python's slicing. The [::-1] slice reverses the order of the list elements.

4. Finally, we use the join() method to combine the reversed list of words into a single string, using a space as the delimiter. This gives us the final output where the words in the string are reversed.

Comments