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

Support Django Central

If you appreciate my work, or if it has helped you along your journey. It would mean a lot to me if you could write a message on my wall and share a cup of coffee (or tea) with me.
Buy Me a Coffee at ko-fi.com

2 thoughts on “Python Program To Reverse a Sentence”

    • Hello Manasa you can do the same using ,

      input_word = “hello how are you ”

      # convert it into list
      lst = input_word.split()

      # reverse the word you want to eg:- here it is “how”
      rev_word = lst[1][::-1]

      # replace the reversed word with the original word in the same list
      lst[1]= rev_word

      # print the same
      print(” “.join(lst))

      Reply

Leave a Comment