Problem Definition Create a python program to reverse a sentence. Algorithm Take a string as input. Convert the sentence into a list of words. 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
The post Python Program To Reverse a Sentence appeared first on Django Central.
from Planet Python
via read more
No comments:
Post a Comment