How to Remove Spaces from String in Python

Contents
In this article, you will learn how to remove spaces from string in Python.
Remove Spaces from String
In Python, you can remove spaces from a string using several methods. Here are some of them:
Using replace() method
The replace() method is used to replace a substring with another substring. You can use it to replace spaces with an empty string to remove spaces from the string.
string_with_spaces = "Hello World! How are you?"
string_without_spaces = string_with_spaces.replace(" ", "")
print(string_without_spaces)
# Output: HelloWorld!Howareyou?
Using join() method
The join() method is used to concatenate a list of strings into a single string. You can split the original string into a list of substrings using the split() method and then join them without spaces to remove spaces from the string.
string_with_spaces = "Hello World! How are you?"
string_list = string_with_spaces.split()
string_without_spaces = "".join(string_list)
print(string_without_spaces)
# Output: HelloWorld!Howareyou?
Using a loop
You can use a loop to iterate over each character in the string and append non-space characters to a new string.
string_with_spaces = "Hello World! How are you?"
string_without_spaces = ""
for char in string_with_spaces:
if char != " ":
string_without_spaces += char
print(string_without_spaces)
# Output: HelloWorld!Howareyou?
Using regular expressions
You can use the re module in Python to replace all whitespace characters (including spaces, tabs, and newlines) with an empty string.
import re
string_with_spaces = "Hello World! How are you?"
string_without_spaces = re.sub(r'\s+', '', string_with_spaces)
print(string_without_spaces)
# Output: HelloWorld!Howareyou?
Using list comprehension
You can remove spaces from a string in Python by using list comprehension.
string_with_spaces = "Hello World! How are you?"
string_without_spaces = ''.join([i for i in string_with_spaces if i != ' '])
print(string_without_spaces)
# Output: HelloWorld!Howareyou?
Using the filter() function and lambda expression
You can remove spaces from a string in Python using the filter() function and lambda expression.
string_with_spaces = "Hello World! How are you?"
string_without_spaces = ''.join(filter(lambda x: x != ' ', string_with_spaces))
print(string_without_spaces)
# Output: HelloWorld!Howareyou?
Using the translate() method and string.maketrans() function
You can remove spaces from a string in Python by using the translate() method and string.maketrans() function.
import string
string_with_spaces = "Hello World! How are you?"
table = string.maketrans("", "", " ")
string_without_spaces = string_with_spaces.translate(table)
print(string_without_spaces)
# Output: HelloWorld!Howareyou?