Remove spaces from a string in Python

How Do You Remove Spaces From a Python String?

Are you wondering how to remove spaces from a string in Python? You are in the right place, keep reading, you will know how to do it quickly.

There are multiple ways to remove spaces from a Python string. The simplest approach is to use the string replace() method. If the spaces to remove are just at the beginning and at the end of the string the strip() method also works fine. An alternative approach is to use a regular expression.

We will start with the approach that works in most cases and then look at other options to give you a more complete knowledge of the topic.

Spaces, we are coming for you!

How to Remove all Spaces from a String in Python

The easiest approach to remove all spaces from a string is to use the Python string replace() method.

Let’s apply this method to the string below:

>>> message = " Welcome to Codefather.tech "
>>> print(message.replace(" ",""))
WelcometoCodefather.tech 

The replace() method replaces the occurrences of the substring passed as first argument (in this case the space ” “) with the second argument (in this case an empty character “”).

It also provides an optional third argument that allows to specify how many occurrences of the first substring (in this case the space) you want to replace.

>>> print(message.replace(" ","", 2))
Welcometo Codefather.tech  

As you can see the first and second spaces have been replaced with an empty character but the third space has not been replaced.

Quite handy!

Note: the replace method returns a copy of the original string considering that Python strings are immutable.

What if you want to replace whitespaces with underscoscores?

To replace whitespaces in a Python string with underscores you can use the following command:

>>> message.replace(" ","_")
'_Welcome_to_Codefather.tech_' 

How to Strip all Whitespaces from a String Using Python

An alternative way to remove whitespaces from a string is to use the split() and join() functions.

Firstly, we apply the split() function to our string:

>>> message.split()
['Welcome', 'to', 'Codefather.tech'] 

Interesting…

…the split() method converts our string into a list of strings and takes away all the whitespaces.

This means that we can then use the string join() method to put the items of the list together.

The join() method has the following syntax:

"{string_to_be_used_as_separator}".join(iterable)

And here is how you can use it in practice and apply it to an empty string.

>>> "".join(message.split())
'WelcometoCodefather.tech' 

Nice!

If you want to keep the spaces between the three words you can use the following instead…

>>> message = " Welcome to Codefather.tech "
>>> " ".join(message.split())
'Welcome to Codefather.tech' 

How to Remove Spaces From the Beginning of a String in Python

What if you only want to remove spaces from the beginning of a string?

Let’s say we have the following string…

>>> message = "    Hello" 

To remove leading spaces you can use the string lstrip() method.

>>> print(message.lstrip())
Hello 

This method will not remove any trailing spaces.

Remove Trailing Spaces from a Python String

To remove trailing spaces from a string Python provides the rstrip() string method.

>>> message = "    Hello   "
>>> print(message.rstrip())
     Hello 

Ok, we can see that the leading spaces have not been removed. But it’s a bit tricky to confirm that the trailing spaces have actually been removed considering that we cannot see them.

Let’s try something to confirm they have been removed.

>>> print(len(message))
12
>>> print(len(message.rstrip()))
9 

By using the len() function we can confirm that three characters (the trailing spaces) have been removed from the string.

Remove Spaces from Beginning and End of a String in Python

In the previous two sections we have seen that Python provides two string methods to remove spaces from the beginning and the end of a string.

What if we want to remove spaces both at the start and the end of a string with a single line of code?

To remove spaces from the beginning and the end of a string you can use the string strip() method.

>>> message = "    Hello   "
>>> print(message.strip())
Hello
>>> print(len(message.strip()))
5 

The string returned by the strip() method has only 5 characters because spaces both at the beginning and at the end of the string have been removed.

In theory you could also apply the lstrip() and rstrip() method in a single line of code and achieve the same result.

>>> print(message.lstrip().rstrip())
Hello
>>> print(len(message.lstrip().rstrip()))
5 

Notice how Python allows to apply two methods in a single line of code using the dot notation.

You now know how to remove spaces from both ends of a string.

How to Remove Extra Spaces Between Words from a String with Python

There might be a scenario where you don’t want to replace all the spaces in a string, you just want to remove some extra spaces.

For example, let’s say you want to replace two consecutive spaces (where present) with a single space.

>>> message = "Hello  from  Codefather" 

Between the three words there are two spaces and I want to replace them with one. To do that we can use the replace() method.

>>> print(message.replace("  ", " "))
Hello from Codefather 

We pass the two consecutive spaces as first argument (” “) and a single space as second argument (” “).

Using Python Regular Expressions to Remove Spaces from a String

Let’s analyse a different approach to remove spaces from a string: we will use Python regular expressions.

Regular expressions are one of these topics many developers avoid especially at the beginning of their coding career.

But…

…regular expressions are very powerful and it’s a good practice to use them often in order to become more and more used to them.

The module to handle regular expressions in Python is called re. To remove spaces from a Python string we will use the re.sub() function.

Here is the syntax of the re.sub() function:

re.sub(pattern_to_be_replaced, replacement_pattern, string)
>>> message = "Hello  from  Codefather"
>>> re.sub("\s", "", message) 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 're' is not defined 

Can you see the NameError exception above?

It’s caused by the fact that we haven’t imported the re module first.

>>> import re 
>>> re.sub("\s+", "", message)
'HellofromCodefather' 

Let’s look at the pattern to be replaced considering that the other two arguments are pretty straightforward.

What does “\s+” mean?

The pattern \s+ applied to a Python regular expression matches whitespace characters (including [ \t\n\r\f\v]). If you replace the lower case s with a capital s (“\S+”) the pattern matches any non-whitespace characters.

>>> re.sub("\S+", "", message)
'    ' 

Makes sense?

Using a Regular Expression to Replace Spaces at the Beginning of a String

A regular expression can also be used to replace spaces at the beginning of a string by adding an extra character to the pattern we have used before.

>>> re.sub("^\s+", "", message)
'Hello  from  Codefather  ' 

We have added the ^ character at the beginning of the pattern to refer to the beginning of the line.

The result is the same you get with the lstrip() method.

>>> message.lstrip()
'Hello  from  Codefather  ' 

Using a Regular Expression to Replace Spaces at the End of a String

We can use regular expression as alternative to the rstrip() method to remove trailing spaces from a string.

Let’s see what else we have to add to the regular expression pattern to make it happen.

>>> re.sub("\s+$", "", message)
'  Hello  from  Codefather' 

Adding the $ at the end of the “\s+” pattern allows to match only the whitespaces at the end of the string.

The result is the same as the rstrip() method…

>>> message.rstrip()
'  Hello  from  Codefather' 

Conclusion

You now have enough ways to replace or remove white spaces in Python strings.

Just pick the one you prefer and that also fits the specific scenario you are dealing with.

Keep learning…keep coding…keep growing! 😀

Share knowledge with your friends!

Leave a Reply

Your email address will not be published. Required fields are marked *