Python – Move Word to Rear end

Sometimes, while working with Python strings, we can have a problem in which we need to find a word and move it to end of the string. This can have application in many domains including day-day programming and school programming. Lets discuss certain ways in which this task can be performed.

Method #1 : Using replace() + "+" operator
The combination of above functions can be used to perform this task. In this, we replace the element with empty string and append the work to end of string to perform this task.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Move Word to Rear end
# Using replace() + "+" operator
  
# initializing string
test_str = 'Geeksforgeeks is best for geeks '
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing Substring
sub_str = 'best'
  
# Move Word to Rear end
# Using replace() + "+" operator
res = test_str.replace(sub_str, "") + str(sub_str)
  
# printing result 
print("The string after word removal : " + str(res)) 

chevron_right


Output :

The original string is : Geeksforgeeks is best for geeks 
The string after word removal : Geeksforgeeks is  for geeks best

 

Method #2 : Using string slicing and find()
The combination of above functionalities can also be used to perform this task. In this, we construct the list of string and join it again after performing move using find() and slicing.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Move Word to Rear end
# Using string slicing and find()
  
# initializing string
test_str = 'Geeksforgeeks is best for geeks '
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing Substring
sub_str = 'best'
  
# Move Word to Rear end
# Using string slicing and find()
res = test_str[:test_str.find(sub_str)] + test_str[test_str.find(sub_str) + len(sub_str):] + sub_str
  
# printing result 
print("The string after word removal : " + str(res)) 

chevron_right


Output :

The original string is : Geeksforgeeks is best for geeks 
The string after word removal : Geeksforgeeks is  for geeks best



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.