Python: Move all spaces to the front of a given string in single traversal

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

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

Let’s see some sample test cases before going to the coding.

Input:
string = "sirf  padhai "

Output:-


"sirfpadhai" -> output will be without quotes

First Programs:-

## initializing the string
string = "I am a software engineer."

## finding all character exclusing spaces
chars = [char for char in string if char != " "]

## getting number of spaces using count method
spaces_count = string.count(' ')

## multiplying the space with spaces_count to get all the spaces at front of the ne
w_string
new_string = " " * spaces_count

## appending characters to the new_string
new_string += "".join(chars)

## priting the new_string
print(new_string)

Output:-

If you run the above program, you will get the following output.

Iamasoftwareengineer

Flowchart:-

Sirf Padhai

Second Programs:-

def moveSpaces(str1): 
    no_spaces = [char for char in str1 if char!=' ']   
    space= len(str1) - len(no_spaces)
    # Create string with spaces
    result = ' '*space    
    return result + ''.join(no_spaces)
  
s1 = "Python programmer"
print("Original String:\n",s1)
print("\nAfter moving all spaces to the front:")
print(moveSpaces(s1))

Output:-

Original String:
Python programmer

After moving all spaces to the front:
 Pythonprogrammer

Previous articlePython: move spaces to the front of a given string
Next articleDBMS course syllabus-CS-502

LEAVE A REPLY

Please enter your comment!
Please enter your name here