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

Capturing Query Parameters of request.get in Django

In Django, the request object contains a variety of information about the current HTTP request, including the query parameters. Query parameters are a way to pass additional information in the URL and are used to filter or sort data. The request object p…
Read more →

2 min read

Understanding related_name in Django Models

In Django, related_name is an attribute that can be used to specify the name of the reverse relation from the related model back to the model that defines the relation. It is used to specify the name of the attribute that will be used to access the relat…
Read more →

2 min read