Python: Reverse Words in String

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

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

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare