Python Program To Reverse a Sentence

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

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Close