w3resource

Python: Remove spaces from a given string

Python String: Exercise-57 with Solution

Write a Python program to remove spaces from a given string.

Visual Presentation:

Python String: Remove spaces from a given string.

Sample Solution:

Python Code:

# Define a function 'remove_spaces' that takes a string 'str1' as input.
def remove_spaces(str1):
    # Use the 'replace' method to remove spaces (' ') in the input string 'str1'.
    str1 = str1.replace(' ', '')
    return str1  # Return the modified string without spaces.

# Call the 'remove_spaces' function with different input strings and print the results.
print(remove_spaces("w 3 res ou r ce"))
print(remove_spaces("a b c"))

Sample Output:

w3resource
abc   

Flowchart:

Flowchart: Remove spaces from a given string

Python Code Editor:

Previous: Write a Python program to find the second most repeated word in a given string.
Next: Write a Python program to move spaces to the front of a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.