Python - Move Word to Rear end
Last Updated :
08 May, 2023
Sometimes, while working with Python strings, we can have a problem in which we need to find a word and move it to the end of the string. This can have application in many domains, including day-day programming and school programming. Let's 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 the end of string to perform this task.
Python3
# 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))
OutputThe original string is : Geeksforgeeks is best for geeks
The string after word removal : Geeksforgeeks is for geeks best
Time Complexity: O(n), where n is the length of the input string "test_str".
Space Complexity: O(n)
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.
Python3
# 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))
OutputThe original string is : Geeksforgeeks is best for geeks
The string after word removal : Geeksforgeeks is for geeks best
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using split(), remove(), append() and join() methods
Python3
# Python3 code to demonstrate working of
# Move Word to Rear end
# 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
x = test_str.split()
x.remove(sub_str)
x.append(sub_str)
res = " ".join(x)
# printing result
print("The string after word removal : " + str(res))
OutputThe original string is : Geeksforgeeks is best for geeks
The string after word removal : Geeksforgeeks is for geeks best
Method #4: Using the re module
Python3
import re
def move_word_to_rear(test_str, sub_str):
# using re.sub() method to remove the substring
res = re.sub(r'\b' + re.escape(sub_str) + r'\b', '', test_str)
# adding the substring to the end of the string
res += sub_str
return res
test_str = 'Geeksforgeeks is best for geeks '
sub_str = 'best'
print(move_word_to_rear(test_str, sub_str))
OutputGeeksforgeeks is for geeks best
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5: Using String concatenation:
Python3
def move_word_to_end(string, word):
words = string.split()
result = ""
for w in words:
if w != word:
result += w + " "
result += word
return result
test_str = 'Geeksforgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
sub_str = 'best'
print(move_word_to_end(test_str, sub_str))
#This code is contributed by Jyothi pinjala.
OutputThe original string is : Geeksforgeeks is best for geeks
Geeksforgeeks is for geeks best
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #6: Using a list comprehension
Python3
def move_word_to_end(string, word):
words = string.split()
if word not in words:
return string
return ' '.join([w for w in words if w != word]) + ' ' + word
test_str = 'Geeksforgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
sub_str = 'best'
print(move_word_to_end(test_str, sub_str))
#This code is contributed by Vinay Pinjala.
OutputThe original string is : Geeksforgeeks is best for geeks
Geeksforgeeks is for geeks best
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #7: Using regular expressions and re.sub()
Step-by-step approach:
- In this approach, we can use the re.sub() method to find and replace the substring at the end of the string.
- Use the pattern "\b(best)\b" to match the word "best" only if it appears as a whole word.
- Replace it with an empty string and append it at the end of the original string.
Below is the implementation of the above approach:
Python3
import re
# 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 regular expressions and re.sub()
res = re.sub(r'\b' + sub_str + r'\b', '', test_str) + sub_str
# printing result
print("The string after word removal : " + str(res))
OutputThe original string is : Geeksforgeeks is best for geeks
The string after word removal : Geeksforgeeks is for geeks best
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), as we are creating a new string to store the result.
Method # 8: Using string.partition() and string.replace()
- Initialize the string variable test_str and the substring variable sub_str.
- Use the partition() method to split the test_str into three parts - the part before the first occurrence of sub_str, sub_str itself, and the part after sub_str.
- If sub_str is not found in test_str, then partition() will return the original string as the first part, an empty string as the second part, and another empty string as the third part. In this case, set the first part as the modified string res.
- Otherwise, remove all occurrences of sub_str from the first and third parts of the split string using the replace() method, and concatenate them along with sub_str to form the modified string res.
- Print the original string and the modified string.
Python3
# 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'
# split the string using partition() method
part1, found, part2 = test_str.partition(sub_str)
# check if sub_str was found in test_str
if not found:
res = part1
else:
# remove sub_str from part1 and part2
part1 = part1.replace(sub_str, "")
part2 = part2.replace(sub_str, "")
# concatenate the parts with sub_str in between
res = part1 + sub_str + part2
# printing result
print("The string after word removal : " + str(res))
OutputThe original string is : Geeksforgeeks is best for geeks
The string after word removal : Geeksforgeeks is best for geeks
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), for the new string variables created in the process.
Similar Reads
Python - Word starting at Index
Sometimes, while working with Python, we can have a problem in which we need to extract the word which is starting from a particular index. This can have a lot of applications in school programming. Let's discuss certain ways in which this task can be performed. Method #1: Using a loop This is a bru
2 min read
Replace multiple words with K - Python
We are given a string s and the task is to replace all occurrences of specified target words with a single replacement word K.For example, given text = "apple orange banana" and words_to_replace = ["apple", "banana"], the output will be "K orange K".Using List ComprehensionThis is the most efficient
4 min read
Python program to read file word by word
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file word by word.Read file word by wordIn this article, we will look at how to read a text file and split it into single words using Python. Here are a few examples of
2 min read
Python | Replace rear word in String
Sometimes, while working with String list, we can have a problem in which we need to replace the most rear i.e last word of string. This problem has many application in web development domain. Let's discuss different ways in which this problem can be solved. Method #1 : Using split() + join() This i
5 min read
Python | Word Stretch
Write a program to get all possibilities (in sorted order) for stretching a word to the given size. If the list of required indices is passed, then only those combinations present at those indices should be returned. If the required indices are null, then all the combinations have to be returned.Exa
3 min read
Python - Sequence Assignment to Words
Given a String of words, assign an index to each word. Input : test_str = 'geeksforgeeks is best' Output : {0: 'geeksforgeeks', 1: 'is', 2: 'best'} Explanation : Index assigned to each word. Input : test_str = 'geeksforgeeks best' Output : {0: 'geeksforgeeks', 1: 'best'} Explanation : Index assigned
5 min read
Python - Words with Particular Rear letter
Sometimes, we require to get the words that end with the specific letter. This kind of use case is quiet common in the places of common programming projects or competitive programming. Letâs discuss certain shorthands to deal with this problem in Python. Method #1: Using list comprehension + lower()
6 min read
Python - Replace all words except the given word
Given a string. The task is to replace all the words with '?' except the given word K. Examples: Input : test_str = 'gfg is best for geeks', K = "gfg", repl_char = "?" Output : gfg ? ? ? ? Explanation : All words except gfg is replaced by ?. Input : test_str = 'gfg is best for gfg', K = "gfg", repl_
6 min read
Python | Working with .docx module
Word documents contain formatted text wrapped within three object levels. Lowest level- Run objects, Middle level- Paragraph objects and Highest level- Document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the
3 min read
Python - Move Element to End of the List
We are given a list we need to move particular element to end to the list. For example, we are given a list a=[1,2,3,4,5] we need to move element 3 at the end of the list so that output list becomes [1, 2, 4, 5, 3].Using remove() and append()We can remove the element from its current position and th
3 min read