How to Remove Spaces from String in Python?

As a Python developer working on a project for one of my clients, I had a requirement to remove space from a string in Python. After reaching various methods, I found five effective methods to achieve this task. In this tutorial, I will explain all the methods with suitable examples.

Remove Spaces from String in Python

Let us see some important methods to remove spaces from a string in Python.

Read How to Split a String into Equal Parts in Python?

1. Use the str.replace() Method

The str.replace() method is a simple way to remove all spaces from a string. This method replaces occurrences of a specified substring with another substring.

Example:

address = "1600 Pennsylvania Avenue NW"
clean_address = address.replace(" ", "")
print(clean_address)

Output:

1600PennsylvaniaAvenueNW

In the screenshot below you can see the executed example code with the output.

Remove Spaces from String in Python

In this example, we remove all spaces from the address of the White House.

Check out How to Insert a Python Variable into a String?

2. Use str.split() and str.join() Methods

Another effective method is to use str.split() to split the string into a list of words and then str.join() to concatenate them back together without spaces.

Example:

city_name = "New York City"
clean_city_name = "".join(city_name.split())
print(clean_city_name)

Output:

NewYorkCity

In the screenshot below you can see the executed example code with the output.

How to Remove Spaces from String in Python

This method first splits the string “New York City” into a list ['New', 'York', 'City'] and then joins it back into “NewYorkCity”.

Read How to Split a String by Index in Python?

3. Use Regular Expressions

For more complex scenarios, you can use the re module to remove all whitespace characters (spaces, tabs, newlines).

Example:

import re

sentence = "The quick brown fox jumps over the lazy dog"
clean_sentence = re.sub(r'\s+', '', sentence)
print(clean_sentence)

Output:

Thequickbrownfoxjumpsoverthelazydog

In the screenshot below you can see the executed example code with the output.

Remove Spaces from String in Python re

In this example, the regular expression \s+ matches any whitespace character and re.sub() replaces them with an empty string.

Check out Convert Binary to Decimal in Python

4. Use str.strip(), str.lstrip(), and str.rstrip() Methods

These methods are useful for removing leading and trailing spaces from a string. While they don’t remove spaces within the string, they are handy for cleaning up user input.

Example:

name = "  John Doe  "
clean_name = name.strip()
print(f"'{clean_name}'")

Output:

'John Doe'

Here, strip() removes the spaces at the beginning and end of the string.

Read How to Split a String Every N Characters in Python?

5. Use the str.translate() Method

The str.translate() method can be used with str.maketrans() to remove spaces.

Example:

state_name = "California Republic"
clean_state_name = state_name.translate(str.maketrans('', '', ' '))
print(clean_state_name)

Output:

CaliforniaRepublic

This method creates a translation table that maps spaces to None, effectively removing them.

Check out Python Split Regex

Conclusion

In this tutorial, we explored several methods to remove spaces from string in Python, including str.replace() method, str.split() and str.join() method, regular expressions, str.strip(), str.lstrip() and st.rstrip() methods, and str.translate() method with examples.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.