Python code to move spaces to the beginning of a line in one pass

Python Methods and Functions

Examples:

 Input: str = "geeks for geeks" Output: ste = "pythonengineering" Input: str = "move these spaces to beginning" Output: str = "movethesespacestobeginning" There were four space characters in input, all of them should be shifted in front. 

This problem has an existing solution, please refer to lists
Approach :

  1. Step down the input line and create a line without a space using a list comprehension.
  2. Now to see how many whitespace was in the original line, just take the difference in the length of the original line and the newline.
  3. Now create another line and add a space at the beginning.

# Function to move spaces to the beginning of the line
# in single traversal in Python

 

def moveSpaces ( input ):

 

# Move the line to create a line without spaces

  noSpaces = [ch for ch in input if ch! = '' ]

 

# calculate the number of spaces

  space = len ( input ) - len (noSpaces)

 

# create result string with spaces

result = '' * space

 

# concatenate spaces with a string without spaces

result = & # 39; & quot; & # 39; + result + & # 39; & # 39; .join (noSpaces) + & # 39; & quot; & # 39;

print result

 
# Driver program

if __ name__ = = "__ main__" :

input = 'geeks for geeks '

  moveSpaces ( input )

Exit :

 "pythonengineering" 




Get Solution for free from DataCamp guru