Instagram
youtube
Facebook
Twitter

Remove Blank Spaces from a String

A Python program to remove all blank spaces from a string using the replace() method.

Here's a point-wise explanation of your code:

  1. Function Definition
    def remove_spaces(string):
    – A function named remove_spaces is defined that takes one argument string.

     
  2. Removing Spaces
    return string.replace(" ", "")
    – The replace() method removes all spaces (" ") by replacing them with an empty string ("").

     
  3. Input String
    text = "Hello World, Python is fun!"
    – A sample string with spaces is assigned to the variable text.

     
  4. Function Call
    result = remove_spaces(text)
    – Calls the function and stores the returned string (without spaces) in result.

     
  5. Print Output
    print("String without spaces:", result)
    – Displays the modified string without any spaces

 

Program:

def remove_spaces(string):

    return string.replace(" ", "")

text = "Hello World, Python is fun!"

result = remove_spaces(text)

print("String without spaces:", result)