How to remove spaces from a string in python?

This article will introduce different methods to remove spaces in a messy Python string based on different scenarios and requirements. After reading, you can choose the most appropriate way for your code. More importantly, you will feel the flexibility and elegance of Python again.

Spaces are also considered as a character inside a string, and sometimes unnecessary spaces in the string cause wrong results.

For example, instead of typing ‘Alex’, a person typed his name ‘Alex  ‘ (see two spaces at the end of the string), and if we compare them using the ‘==’ operator.

To remove spaces from a string you can use any of the following methods:

  • By using strip() method
  • By using replace() method
  • By using join() with split() method
  • By using translate() method
  • By using Regular Expressions

How to remove spaces from a string in python?

1. Remove Leading and Trailing Spaces of a Python String

The simplest case is that all the leading and trailing spaces of a string are unnecessary. For this, we can just use the strip() function to remove them all.

For example:

The strip() method:

quote = "   Programming is cool.   "
clean_quote = quote.strip()
print(clean_quote)
# Programming is cool.

The above code shows how easy it is to use the strip() function. There is one thing worth to mention: Strings are immutable in Python. The original quote string was not changed. We need to assign the result to a new string after removed the spaces.

In addition, there are two variants of the strip() function:

  • lstrip(): only remove the leading spaces of a string
  • rstrip(): only remove the trailing spaces of a string

Python lstrip() method:

If you want to remove spaces in the beginning of a string , use lstrip().

Python rstrip() method

If you want to remove spaces in the end of a string , use rstrip().

All three string functions strip lstrip, and rstrip can take parameters of the string to strip, with the default being all white space.

2. Remove All Spaces of a Python String

Since removing spaces of a string is the same as replacing every space by an empty character, we can use the replace() function to do this job. This is a common method for cases that we need to remove all spaces of a string.

The replace() method:

name = " Pro  gra   mming   "
clean_name = name.replace(' ', '')
print(clean_name)
# Programming

3. Another Way To Remove All Spaces of a Python String

Python is very flexible and there is another choice for us to do the same job as the replace() function — the translate() function.

The translate() method:

name = " Pro  gra   mming   "
clean_name = name.translate({ord(' '): None})
print(clean_name)
# Programming

The above code shows the usage of this function. If it looks intuitive at the first glance, no worries at all. We just need to know the two rules of its argument:

  • It must be a dictionary or a mapping table.
  • If it’s a dictionary, we must use ASCII rather than characters.

The second rule is easy to follow. We can just use the built-in ord() function to convert a character into its corresponding ASCII.

The first rule gives us more flexibility. If we need to change many characters instead of just spaces, writing the ord() many times may be annoying. In this case, we can use the maketrans() function to generate a mapping table from the original characters at first:

name = " Pro  gra   mming   "
map_table = name.maketrans({' ': None})
clean_name = name.translate(map_table)
print(clean_name)
# Programming

An alternative example of the Python translate() method:

If you want to remove all Whitespaces includes space, tabs, and CRLF. So an elegant and one-liner string function you can use is translate():

>>> str = " Python translate() method "
>>> print(str.translate(str.maketrans('', '', ' \n\t\r')))

Output: 
Pythontranslate()method

OR if you want to remove only whitespace :

import string
>>> str = " Python translate() method "
>>> print(str.translate(str.maketrans('', '', string.whitespace)))

Output: 
Pythontranslate()method

4. Remove Duplicate Spaces of a Python String

Sometimes, we need to eliminate duplicate spaces of a string instead of removing all spaces. In this scenario, we can use the following two functions together:

join() with split() :

  • split(): To split a string into a list based on a separator (any whitespace by default)
  • join(): To combine all items in a list into a string using a separator
quote = "   Programming   is   cool."
new_quote = ' '.join(quote.split())
print(new_quote)
# Programming is cool.

As the above example shows, the idea is clear:

  1. Split all words into a list. So the duplicate spaces are avoided.
  2. Combine all words again by the expected separator — ' '.

5. Use Regular Expressions To Remove Spaces as You Like

Remove Whitespaces from String using Regex- Python

The previous four ways are useful enough for many simple scenarios. However, real data may be very complicated and messy. The previous ways cannot handle all cases. (If you are a data scientist and cleaning messy data is part of your job, you will agree with me.)

Therefore, we sometimes have to use the ultimate weapon for string manipulations — the regular expression (RegEx).

If you are familiar with RegEx, all previous four examples can be handled by it easily. For more complicated cases, RegEx will sort them out as well.

For example, if we need to remove any two consecutive spaces in a string, but keep all single spaces, the previous four ways may be hard to help. But the RegEx, as the ultimate weapon, can do us a favor:

import re

quote = "  Pro  gramming is co  o  l."
new_quote = re.sub(r"\s{2}", "", quote)
print(new_quote)
# Programming is cool.

How to remove all duplicate whitespaces in the string?

If you want to remove all the duplicate whitespaces and newline characters, then you can use join() function with string split() function.

  1. split(): Returns a list of all words in the string separated using delimiter string. If the delimiter is not mentioned, by default whitespace is the delimiter.
  2. join(): This method takes all items in the iterable and combines them into a string using a separator.
import re
str = "      Python     remove    whitespace    "
str = " ".join(re.split("\s+", str, flags=re.UNICODE))
print(str)

Conclusion

Removing spaces of a Python string is a common task for developers. For some simple scenarios, some built-in functions of Python are useful enough. For more complicated cases, the RegEx is the ultimate weapon.

In this article we have implemented various techniques to remove white-spaces from an input string in Python.

Hope you learned something from this post.

Follow Programming Articles for more!

About ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ

Linux and Python enthusiast, in love with open source since 2014, Writer at programming-articles.com, India.

View all posts by ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ →