Python program to remove spaces from a string

Remove spaces from a string

Space between the strings represents the string of a sentence. A sentence may contain many words and each word join another word with a space in it that tells us about the completion of the word and start of another word so readability is maintained. In this python program, we will remove spaces between the words whether the sentence is meaningful or meaningless and we can do this in two different ways:-

  • By traversing the string and removing spaces.
  • Using the join function.

We will learn how to remove spaces from string using the join function as it is easier and not much difficult to understand.

remove spaces from string

Method 1


  • Step 1:- Start.
  • Step 2:-  Take String Input.
  • Step 3:- Use join function to remove spaces.
  • Step 4:- Print String.
  • Step 5:- End.
python program to remove spaces from string

Python code

#take user input 
String = input("Enter the string :") 

#Use join function 
String = "".join(String.split()) 

#print String 
print("After removing spaces string is :",String)


Enter the string :PrepInsta is fabulous
After removing spaces string is : PrepInstaisfabulous

Method 2

Algorithm :

  • Take a string as an input from the user.
  • Count number of spaces in the string and store it in a variable say t
  • Use a loop to call replace() function t times
  • Replace space character with ” in a string.
  • Print output.

Python code

# Python3 program to remove

# spaces from a string

# Input string
s=input("Enter a string: ")

# Count no. of spaces in a string
t=s.count(" ")

# replcae all the spaces with ”
for i in range(t):
s=s.replace(' ',"")

# Print the output
print("String after removing space: ")


Enter a string: PrepInsta is fabulous
String after removing space: