Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

Python Program To Reverse a Sentence

1 min read

Problem Definition

Create a python program to reverse a sentence.

Algorithm

  1. Take a string as input.
  2. Convert the sentence into a list of words.
  3. Join the list in the reverse order which ultimately is the reversed sentence.

Program

sentence = "dread it run from it destiny still arrives"
word_list = sentence.split()
reversed_list = word_list[:: -1]
reversed_sentence = " ".join(reversed_list)
print(reversed_sentence)

Output

arrives still destiny it from run it dread

This program can be further be compressed.

sentence = "dread it run from it destiny still arrives"
print(" ".join(sentence.split()[::-1]))

Output

arrives still destiny it from run it dread

Python lists can be reversed using the reversed() method, which can be used in place of list[ : : -1] in the program as follows.

sentence = "dread it run from it destiny still arrives"
word_list = sentence.split()

reversed_list = reversed(word_list)
reversed_sentence = " ".join(reversed_list)
print(reversed_sentence)

Program for user-provided input

sentence = input("Enter a sentence :")
print(" ".join(reversed(sentence.split())))

Output

Enter a sentence :This is an input
input an is This


PROGRAMS

Latest Articles

Latest from djangocentral

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access serializer.data, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read