Python Forum
Reverse the string word - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Reverse the string word (/thread-23080.html)



Reverse the string word - sneha - Dec-10-2019

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))



RE: Reverse the string word - stullis - Dec-10-2019

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])



RE: Reverse the string word - sneha - Dec-12-2019

Thank you for help.
Now i completely understand the code.. Thank you sir.