Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reverse the string word
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] 
			result+=' '
			end = i 
	start = 0
	while start!=end: 
	return result 

# Driver Code 
str = 'I AM A GEEK'
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.

Possibly Related Threads…
Thread Author Replies Views Last Post
  Reverse a String ragav_in 3 661 Jul-24-2020, 02:24 AM
Last Post: ragav_in
  Reverse word xSphere 6 1,811 Jul-02-2020, 04:10 PM
Last Post: pyzyx3qwerty
  Python Speech recognition, word by word AceScottie 6 10,640 Apr-12-2020, 09:50 AM
Last Post: vinayakdhage
  filter just with the string word jacklee26 2 900 Feb-03-2020, 03:25 PM
Last Post: snippsat
  Cannot Remove the Double Quotes on a Certain Word (String) Python BeautifulSoup soothsayerpg 5 3,510 Oct-27-2019, 09:53 AM
Last Post: newbieAuggie2019
  print a word after specific word search evilcode1 8 1,649 Oct-22-2019, 08:08 AM
Last Post: newbieAuggie2019
  String slicing in python from reverse ift38375 1 1,001 Apr-29-2019, 06:58 AM
Last Post: perfringo
  Word replace with string dabozz 1 1,066 Feb-13-2019, 03:11 PM
Last Post: ichabod801
  Replacing all letters in a string apart from the first letter in each word Carbonix 9 2,460 Jan-17-2019, 09:29 AM
Last Post: buran
  Creating list out of the first letter of every word in a string Drone4four 5 19,621 Oct-05-2018, 09:42 PM
Last Post: volcano63

Forum Jump:

User Panel Messages

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