Python: Move all spaces to the front of a given string in single traversal
Move spaces to front in single traversal.
Write a Python program to move all spaces to the front of a given string in a single traversal.
Visual Presentation:
Sample Solution:
Python Code:
# Function to move spaces to front
def moveSpaces(str1):
# List comprehension to remove spaces
no_spaces = [char for char in str1 if char!=' ']
# Get number of spaces
space = len(str1) - len(no_spaces)
# Create string with required spaces
result = ' '*space
# Return moved spaces + string without spaces
return result + ''.join(no_spaces)
# Test string
s1 = "Python Exercises"
# Print original string
print("Original String:\n",s1)
# Print message
print("\nAfter moving all spaces to the front:")
# Print result
print(moveSpaces(s1))
Sample Output:
Original String: Python Exercises After moving all spaces to the front: PythonExercises
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to traverse a string once and build a new string with all spaces moved to the beginning.
- Write a Python program to implement a single-pass algorithm that separates spaces and non-space characters and then concatenates them with spaces first.
- Write a Python program to use a loop to partition a string into spaces and other characters in one traversal and recombine them.
- Write a Python program to iterate through a string, collecting space characters in one list and others in another, then merge them with spaces at the front.
Python Code Editor:
Previous: Write a Python program to create a string from two given strings concatenating uncommon characters of the said strings.
Next: Write a Python code to remove all characters except a specified character in a given string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics