Write a Python program to move all spaces to the front of a given string in single traversal


The program takes an input string and moves all spaces to the front of the string. Here's a step by step explanation of the code:

  • The first line defines the input string "str1".
  • The "print" statement outputs the original string to the console.
  • The next line creates a list "no_spaces" that contains all characters in "str1" except spaces. This is done using a list comprehension that filters out all spaces using an "if" condition.
  • The next line calculates the number of spaces in the original string by subtracting the length of the "no_spaces" list from the length of the original string "str1". The result is stored in a variable "space".
  • The next line creates a string "result" that consists of "space" number of spaces.
  • The last line concatenates the "result" string and the "no_spaces" list, which now only contains non-space characters, into a single string and outputs it to the console using the "join" method.

Source Code

str1 = "Tutor Joes Computer Education"
print("Original String :",str1) 
no_spaces = [char for char in str1 if char!=' ']   
space= len(str1) - len(no_spaces)
result = ' '*space    
print("\nAfter moving all spaces to the front:",result + ''.join(no_spaces))

Output

Original String : Tutor Joes Computer Education

After moving all spaces to the front:    TutorJoesComputerEducation


Example Programs