Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reverse the string word
#1
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))
Reply
#2
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])
Reply
#3
Thank you for help.
Now i completely understand the code.. Thank you sir.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Retrieve word from string knob 4 431 Jan-22-2024, 06:40 PM
Last Post: Pedroski55
  extract substring from a string before a word !! evilcode1 3 491 Nov-08-2023, 12:18 AM
Last Post: evilcode1
  Isolate a word from a long string nicocorico 2 1,498 Feb-25-2022, 01:12 PM
Last Post: nicocorico
  printing a string in reverse Skaperen 2 1,500 Nov-20-2021, 05:08 AM
Last Post: ghoul
  I am trying to reverse a string using loop codinglearner 4 2,128 Sep-28-2021, 10:46 PM
Last Post: Pedroski55
  change string in MS word Mr_Blue 8 3,213 Sep-19-2021, 02:13 PM
Last Post: snippsat
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,455 Aug-12-2021, 04:25 PM
Last Post: palladium
  Reverse a String ragav_in 3 2,137 Jul-24-2020, 02:24 AM
Last Post: ragav_in
  Reverse word xSphere 6 3,684 Jul-02-2020, 04:10 PM
Last Post: pyzyx3qwerty
  Python Speech recognition, word by word AceScottie 6 15,857 Apr-12-2020, 09:50 AM
Last Post: vinayakdhage

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020