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
author's image
Abhijeet Pal Author and Editor in Chief @djangocentral

Abhijeet is a full-stack software developer from India with a strong focus on backend and system design. He is driven by the need to create impactful solutions that add value to the internet in any way possible.

LinkedIn Twitter Github

Latest Articles

Latest from djangocentral

Django 4.1 adds async-compatible interface to QuerySet

The much-awaited pull request for an async-compatible interface to Queryset just got merged into the main branch of Django.Pull Request - https://github.com/django/django/pull/14843 The Django core team has been progressively adding async suppor…
Read more →

3 min read

Making Django Admin Jazzy With django-jazzmin

Django admin is undoubtedly one of the most useful apps of Django. Over the years there has been very little change in the admin app as far as the UX is concerned and it's not a bad thing at all. Django admin was designed to provide a simple and minimali…
Read more →

4 min read