How To Remove Spaces From a String in Python?

Learn all the methods to remove spaces from a string in Python such as strip(), lstrp(), rstrip(), replace(), split() & join(), Regular Expressions, translate() and isspace().

Real-World Analogy

Imagine you are parking multiple cars in a parking lot, one after another. Instead of parking them close to each other in the designated spots, you leave too much space between them. This will not only waste parking space but will also make the parking lot look disorganized and messy.

Same is the case with spaces in a string in Python. If there are too many unnecessary spaces between words or characters, it makes the string look messy and harder to read. Additionally, these spaces also occupy more memory. By removing these extra spaces, you can clean up the string, making it more organized and easier to work with.

Ways To Remove Spaces From a String in Python

In Python, there are several methods to remove spaces from a string. We will be discussing all of them using code, real life examples and visual analogies.

1. strip() Method

In Python, one of the easiest ways to remove spaces from a string is by using the strip() method, which is a pre-defined function. The strip() method removes all leading spaces (spaces at the beginning of a string) and trailing spaces (spaces at the end of a string) from a string. Keep in mind that the strip() method is only used to remove leading and trailing spaces, It does not remove any spaces from the middle of the string.

Syntax

string.strip()

Code

original_string = "       H el lo W  o r ld      "
substring = original_string.strip()
print(substring)

Output

H el lo W  o r ld

2. rstrip() Method

The rstrip() method is a variation of the strip() method, but it only removes spaces from the right side of the string. The name rstrip() stands for “right strip”.

Syntax

string.rstrip()

Code

original_string = "       H el lo W  o r ld      "
substring = original_string.rstrip()
print(substring)

Output

       H el lo W  o r ld

3. lstrip() Method

The lstrip() method is the second variation of the strip() method which stands for “left strip”. The lstrip() method removes all the leading spaces from a string.

Syntax

string.lstrip()

Code

original_string = "       H el lo W  o r ld      "
substring = original_string.lstrip()
print(substring)

Output

H el lo W  o r ld    

Difference Between strip() , lstrip() and rstrip

The main difference between the three methods is that, the strip() removes spaces from both, beginning and ending of a string. The lstrip() removes spaces only from the beginning of the string while the rstrip() removes spaces only from the ending of the string.

remove spaces from a string: lstrip(), rstrip(), strip()

4. replace() Method

In Python, the replace() method is used to replace a part of a string (substring) by another string. You can use this method to replace all the spaces by an empty string.

Syntax

The replace() method takes two arguments:

  • old_value : The substring which you want to replace (in this case, a space)
  • new_value : The new substring (in this case, an empty string to remove the spaces).
string.replace(old_value, new_value)

Code

original_string = "       H el lo W  o r ld      "
substring = original_string.replace(" ", "")
print(substring)

Output

HelloWorld

5. The split() and join() method

In Python, The split() method takes a character or a word as a parameter and breaks the string wherever it finds the word or character passed to it. When the split() method is called, it divides the string into smaller substrings and returns a list. This list contains all the substrings at each index, in order.

The join() method combines a list of strings into one string. We’ll use the list created by the split() method. To do this, we call join() with a separator. The separator goes between each part of the string. In our case, we don’t want anything between the parts, so we’ll use an empty string as the separator. The list is given to the join() method, which returns a new string.

split() and join() method
Separating different links of a chain

Syntax

split_string = string.split()
clean_string = "separator".join(split_string)

Code

original_string = "       H el lo W  o r ld      "
splitted_string = original_string.split()
substring = ''.join(splitted_string) 
print(substring)

Output

HelloWorld

6. Regular Expressions To Remove Spaces

Regular Expression (Regex) is a powerful tool that is used for string manipulation. You can use regular expressions to eliminate all unnecessary spaces from a string using it’s sub() method. To use regular expressions, first you need to import the re module. Once the re module is imported, you can use it’s sub() method to replace all the spaces of a string with empty strings.

Syntax

The sub() method takes 3 parameters:

  • pattern : The pattern in the string you want to replace (in this case, a space).
  • replacement : what you want to replace it with (in this case, an empty string).
  • string : The string in which you want to make changes.
import re
re.sub(pattern, replacement, string)

Code

import re 
original_string = "       H el lo W  o r ld      "
substring=re.sub(r' ','',original_string)
print(substring)

Output

HelloWorld

7. The translate() Method

The translate() method replaces characters or a  part of a string (substring) based on a translation table. A translation table is similar to a dictionary in Python. It is like a set of instructions telling Python which characters to change. To use the translate() method, you first need to create a translation table using the maketrans() function.

Once the translation table is created, you apply it to the string using the translate() method. This method checks the string against the table and replaces characters according to the instructions in the table. In our case, the key in translation table will be a space, and it’s value will be an empty string.

Syntax

This function takes two parameters.

  • key : The character or substring which you want to replace
  • value : The character or substring which you want to replace it with
translation_table = str.maketrans({key : value})
string.translate(translation_table)

Code

original_string = "       H el lo W  o r ld      "
translation_table = str.maketrans({" ": ""})
substring = original_string.translate(translation_table)
print(substring)

Output

HelloWorld

8. Remove Spaces Using for Loop

In Python, you can use a for loop to manually remove spaces from a string by going through each character of the string and checking if it’s a space. If the character is not space, copy it to the new string and if it is a space then just skip it. There are two methods to do this, i.e the isspace method and the if statement method.

The isspace() Method

In Python, the isspace() method is used to identify spaces in a string. You can use this method to remove spaces by creating an empty string and then adding each character from the original string to it if it is not a space.

Syntax

for char in string:
    if not char.isspace():

Code

In the following code, the for loop iterares over each character in the string, checks if it is a space or a character. It concatenates the character to the new string which is initially empty and skips if it encounters a space.

original_string = "       H el lo W  o r ld      "
substring = ""
for char in original_string:
    if not char.isspace():
        substring += char
print(substring)

Output

HelloWorld

Manually Compare Character

The other approach is to manually compare the character against a space using an if condition in the for loop.

Syntax

for char in string:
    if char != " ":

Code

original_string = "       H el lo W  o r ld      "
substring = ""
for char in original_string:
    if char != " ":
        substring += char
print(substring)

Output

HelloWorld

Comparison Table for All Methods

MethodDescriptionRemoves Spaces From
strip()Removes leading and trailing spaces.Both ends
rstrip()Removes trailing spaces only.Right end
lstrip()Removes leading spaces only.Left end
replace()Replaces all spaces in the string with an empty string.Anywhere in the string
split() & join()Splits the string into a list of substrings and then rejoins them without any spaces.Anywhere in the string
isspace()Checks if a character is a space. You can use this in a loop to filter out spaces.Anywhere in the string
for loopIterates through each character and builds a new string without spaces.Anywhere in the string
translate()Removes spaces by mapping characters and filtering them out using a translation table.Anywhere in the string
RegexUses regular expressions to search for and remove spaces based on patterns.Anywhere in the string

Conclusion

Removing spaces from a string in Python can be done in many ways like strip(), rstrip(), lstrip(), replace(), split() & join(), regular expressions, translate(), isspace() and for loop. Each method has it’s own purpose and the usage of it depends on your needs, so you can pick the one that works best for you.

FAQs

Why would you want to remove spaces from a string in Python?

Removing spaces is important for data cleaning and formatting. It helps make strings more manageable and can improve readability, especially when processing user input or formatting data for display.

What is the simplest way to remove all the spaces from a string in Python?

The simplest method is using the replace() method, which allows you to replace all spaces in the string with nothing (an empty string).

Can I remove only leading and trailing spaces from a string?

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

How does the isspace() method work for removing spaces?

The isspace() method only checks if a character is a space. You can use it in a for loop to create a new string that includes only the characters that are not spaces.

Is it possible to remove spaces manually using a loop?

Yes, you can use a for loop to iterate through each character of the string and build a new string without any spaces.

Leave a Comment

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

Scroll to Top