Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Move Word to Rear end
Moving a word to the rear end of a string means relocating a specific word from its current position to the end of the string. Python provides several approaches to accomplish this task efficiently.
Understanding the Problem
When we move a word to the rear end, we need to:
Identify and remove the target word from its current position
Append the word to the end of the remaining string
Maintain proper spacing in the final result
Using replace() Method
The replace() method removes the target word and we concatenate it at the end ?
# Initialize the string
input_str = 'Hello dear friends, You are reading this article on Tutorials Point'
print("Input string: " + input_str)
# Word to move
move_str = 'reading this'
# Move the word to rear end
after_moving = input_str.replace(move_str, "").strip() + " " + move_str
print("Output string: " + after_moving)
Input string: Hello dear friends, You are reading this article on Tutorials Point Output string: Hello dear friends, You are article on Tutorials Point reading this
Using split() and List Methods
This approach splits the string into words, removes the target word, and appends it back ?
# Initialize the string
input_str = 'Tutorials Point is best platform for learners'
print("Input String: " + input_str)
# Word to move
move_word = 'best'
# Split string into words
words = input_str.split()
# Remove and append the word
if move_word in words:
words.remove(move_word)
words.append(move_word)
# Join back into string
output_str = " ".join(words)
print("Output String: " + output_str)
Input String: Tutorials Point is best platform for learners Output String: Tutorials Point is platform for learners best
Handling Multiple Occurrences
When a word appears multiple times, you might want to move only the first occurrence ?
def move_first_occurrence(text, word):
words = text.split()
if word in words:
# Find and remove first occurrence
index = words.index(word)
words.pop(index)
words.append(word)
return " ".join(words)
# Example with repeated word
text = "Python is great Python language"
word = "Python"
result = move_first_occurrence(text, word)
print(f"Original: {text}")
print(f"Result: {result}")
Original: Python is great Python language Result: is great Python language Python
Comparison
| Method | Time Complexity | Best For | Handles Multiple Words |
|---|---|---|---|
replace() |
O(n) | Simple phrases | Removes all occurrences |
split() + remove() |
O(n) | Single words | Removes first occurrence |
Conclusion
Use replace() for moving phrases or when you want to remove all occurrences. Use split() with list methods when you need more control over which occurrence to move. Both approaches have O(n) time complexity for string operations.
