Python code to move spaces to the front of string in a single traversal



We have a string, and our goal is to move all the spaces in the string to front. Suppose if a string contains four spaces then, we have to move those four spaces in front of every character. Let's see some sample test cases before going to the coding.

Input:
string = "tutorials point "
Output:
"tutorialspoint" -> output will be without quotes


Input:
string = "I am a python programmer."
Output:
"Iamapythonprogrammer." -> output will be without quotes

Let's follow the below steps to achieve our goal.

Algorithm

1. Initialise the string.
2. Find out all the characters which are not spaces and store them in a variable.
3. Find out the no. of spaces by count method of the string.
4. Multiply a space by no. of spaces and store it in a variable.
5. Append all the characters to the previous variable.
6. Print the result at the end.

Let's try to implement the above algorithm.

Example

 Live Demo

## initializing the string
string = "tutorials point "
## 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.

tutorialspoint

Let's execute the program with different input.

Example

 Live Demo

## initializing the string
string = "I am a python programmer."
## 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.

Iamapythonprogrammer.

Conclusion

If you have any doubts regarding the program, mention them in the comment section.


Advertisements