# reverse the order of words in a sentence (python 2.6.1) # you may also be interested # in alphabetizing the words in a sentence def reverseWordOrderOfSentence(sentence): #break the sentence into words with split() words = sentence.split(' ') #reverse the order of the words list #in python 2.6.1 a list.reverse() is done to the calling list object # older versions return a reversed list..... so # words = words.reverse() words.reverse() #iterate through and build the new sentence newSentence = "" for word in words: newSentence += " " + word #return and strip out beginning or trailing white space return newSentence.strip() if __name__ == '__main__': print reverseWordOrderOfSentence("Hooray for Pythonic Prose") #input sentence: # # "Hooray for Pythonic Prose" # #output: # "Prose Pythonic for Hooray"
A python example based blog that shows how to accomplish python goals and how to correct python errors.
Showing posts with label reverse. Show all posts
Showing posts with label reverse. Show all posts
Friday, September 4, 2009
Python reverse word order of a sentence
Subscribe to:
Posts (Atom)