Python Forum

Full Version: Reverse the string word
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello friends,
I am trying to reverse the words present in the string(for eg. I am a student output:student a am I) . I have reference code but i did not understand the exact working of code. can anyone please explain me the working of the code. I am the beginner in the coding.

Here is my code :

def wordReverse(str): 
	i = len(str)-1
	start = end = i+1
	result = '' 

	while i>=0: 
		if str[i] == ' ': 
			start = i+1
			while start!= end: 
				result += str[start] 
				start+=1
			result+=' '
			end = i 
		i-=1
	start = 0
	while start!=end: 
		result+=str[start] 
		start+=1
	return result 

# Driver Code 
str = 'I AM A GEEK'
print(wordReverse(str))
The code assesses the sentence from the end to the beginning. The first while loop checks each character starting from the end until it finds a space. Once it finds a space, it iterates from the index start until index end and writes the word to the result. Then, it continues. The last loop basically does the same thing as the first one to pick up the first word in the original sentence.

Now, this can be written more concisely in Python.

def wordReverse(str): 
    words = str.split() # Split sentence by spaces into a list
    return " ".join(words[::-1])
Thank you for help.
Now i completely understand the code.. Thank you sir.