Skip to content

Instantly share code, notes, and snippets.

@viveksyngh
Created August 9, 2015 19:24
Show Gist options
  • Select an option

  • Save viveksyngh/8a523c244907af445aa1 to your computer and use it in GitHub Desktop.

Select an option

Save viveksyngh/8a523c244907af445aa1 to your computer and use it in GitHub Desktop.
Reverse a string Word by Word
__author__ = 'Vivek'
#reverse the string word by word.
def reverseWords(A):
"""
Reverse the string word by word, removes leading and trailing spaces,
:param: string to be reversed
:return: reversed string word by word
"""
curWord = ''
listOfWords = []
for char in A :
if char != ' ' :
curWord += char
else :
if curWord != '' :
listOfWords.append(curWord)
curWord = ''
if curWord != '' :
listOfWords.append(curWord)
listOfWords.reverse()
return " ".join(word for word in listOfWords)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment