Table of contents
1.
Introduction
2.
Using replace() Method
2.1.
Syntax
2.2.
Example
3.
Removing Leading and Trailing Spaces
3.1.
Example
4.
Removing Leading Spaces Only
4.1.
Example
5.
Remove Spaces from a String in Python Using Regex & itertools  
5.1.
Example string with spaces  
6.
Removing Trailing Spaces Only
6.1.
Example
7.
Remove Spaces from a String in Python Using lstrip() Function
7.1.
Example
8.
Remove Spaces from a String in Python Using `split()` & `strip()` Functions  
8.1.
Using `split()` & `join()`  
8.1.1.
Using `strip()`  
8.1.2.
Combining `split()` & `strip()`  
9.
Remove Spaces from a String in Python Using rstrip() Function
9.1.
Example
10.
Remove Spaces from a String in Python Using NumPy  
11.
Remove Spaces from a String in Python Using isspace() Method
11.1.
Example
12.
Frequently Asked Questions
12.1.
How do I remove all spaces from a string in Python?
12.2.
What is the difference between strip(), lstrip(), and rstrip()?
12.3.
Can I remove spaces using regular expressions?
13.
Conclusion
Last Updated: Mar 17, 2025
Medium

Remove spaces from a string in Python

Author Sinki Kumari
0 upvote

Introduction

Removing spaces from a string in Python can be done using methods like replace(), split() with join(), or regular expressions. This is useful when processing text data where unnecessary spaces need to be eliminated. 

Remove spaces from a string in Python

In this article, we will discuss different ways to remove spaces from a string in Python, along with examples to demonstrate their implementation.

Using replace() Method

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

Syntax

string.replace(old_value, new_value)

Example

text = "Hello World! Python is fun."
new_text = text.replace(" ", "")
print(new_text)
You can also try this code with Online Python Compiler
Run Code

 

Output:

HelloWorld!Pythonisfun.

 

The replace() method removes all spaces from the string by replacing them with an empty string ("").

Removing Leading and Trailing Spaces

Sometimes, a string contains unnecessary spaces at the beginning and end. We can use the strip() method to remove these spaces.

Example

text = "   Hello, Python!   "
new_text = text.strip()
print(new_text)
You can also try this code with Online Python Compiler
Run Code

 

Output:

Hello, Python!

 

The strip() method removes only the spaces at the start and end, keeping the spaces between words intact.

Removing Leading Spaces Only

To remove spaces from the beginning of a string, we use the lstrip() method.

Example

text = "   Python is great."
new_text = text.lstrip()
print(new_text)
You can also try this code with Online Python Compiler
Run Code

 

Output:

Python is great.

 

The lstrip() method removes spaces only from the left side of the string.

Remove Spaces from a String in Python Using Regex & itertools  

Regular expressions (regex) are a powerful tool for pattern matching & text manipulation. Python’s `re` module provides functions to work with regex. To remove spaces from a string using regex, we can use the `re.sub()` function. This function replaces occurrences of a pattern with a specified string.  

Let’s see how you can do it:  

import re  

Example string with spaces  

text = "  Hello   World!  This is Python.  "  


Remove all spaces using regex  

cleaned_text = re.sub(r'\s+', '', text)  
print(cleaned_text)  
You can also try this code with Online Python Compiler
Run Code


Explanation:  

  • `\s+` is a regex pattern that matches one or more whitespace characters (spaces, tabs, or newlines).  
     
  • `re.sub(r'\s+', '', text)` replaces all matches of the pattern with an empty string, effectively removing all spaces.  

Removing Trailing Spaces Only

To remove spaces at the end of a string, we use the rstrip() method.

Example

text = "Python is powerful.   "
new_text = text.rstrip()
print(new_text)
You can also try this code with Online Python Compiler
Run Code


Output:

Python is powerful.

 

The rstrip() method removes spaces only from the right side of the string.

Remove Spaces from a String in Python Using lstrip() Function

The lstrip() function removes spaces from the start of a string but keeps spaces elsewhere.

Example

text = "   Python programming."
new_text = text.lstrip()
print(new_text)
You can also try this code with Online Python Compiler
Run Code


Output:

Python programming.

 

This function is helpful when dealing with user input that may have unintended spaces at the start.

Remove Spaces from a String in Python Using `split()` & `strip()` Functions  

Python provides built-in string methods like `split()` & `strip()` that make it easy to remove spaces from a string. These methods are simple to use & do not require any external libraries. Let’s understand how they work.  

Using `split()` & `join()`  

The `split()` method splits a string into a list of substrings based on a specified delimiter. By default, it splits on whitespace. We can then use `join()` to combine the substrings back into a single string without spaces.  

Let’s see the complete code:  

Example string with spaces  

text = "  Hello   World!  This is Python.  "  


Remove spaces using split() & join()  

cleaned_text = ''.join(text.split())  
print(cleaned_text)  
You can also try this code with Online Python Compiler
Run Code


Explanation:  

  • `text.split()` splits the string into a list of words, automatically removing all whitespace (spaces, tabs, & newlines).  
     
  • `''.join()` joins the list of words into a single string without any spaces.  

Using `strip()`  

The `strip()` method removes leading & trailing spaces from a string. If you only want to remove spaces from the beginning & end of a string, this is the perfect tool.  

Let’s see how you can use it:  

Example string with leading & trailing spaces  

text = "  Hello   World!  This is Python.  "  


Remove leading & trailing spaces using strip()  

cleaned_text = text.strip()  
print(cleaned_text)  
You can also try this code with Online Python Compiler
Run Code


Explanation:  

  • `text.strip()` removes all leading & trailing whitespace from the string.  
     
  • If you want to remove only leading spaces, use `lstrip()`. For trailing spaces, use `rstrip()`.  

Combining `split()` & `strip()`  

If your string has extra spaces between words & you want to clean it up, you can combine `split()` & `strip()`. For example:  

Example string with extra spaces  

text = "  Hello   World!  This is Python.  "  


Remove extra spaces between words & leading/trailing spaces  

cleaned_text = ' '.join(text.split())  

print(cleaned_text)  


Explanation:  

  • `text.split()` splits the string into words, removing all extra spaces.  
     
  • `' '.join()` joins the words back into a single string with a single space between them.  

This method is useful when you want to normalize the spacing in a string.  

Remove Spaces from a String in Python Using rstrip() Function

The rstrip() function removes spaces from the end of a string but does not affect leading spaces.

Example

text = "Python coding.   "
new_text = text.rstrip()
print(new_text)
You can also try this code with Online Python Compiler
Run Code


Output:

Python coding.

 

This is useful when handling formatted data where unnecessary spaces at the end need to be trimmed.

Remove Spaces from a String in Python Using NumPy  

NumPy is a powerful library in Python, primarily used for numerical computations. However, it can also be used for string manipulation tasks, including removing spaces from a string. While NumPy is not the most common choice for this task, it can be useful if you are already working with NumPy arrays or need to process large datasets efficiently.  

Let’s see how you can remove spaces from a string using NumPy:  

Step-by-Step Code  

1. Install NumPy (if not already installed):  

If you don’t have NumPy installed, you can install it using pip:  

   pip install numpy


2. Remove Spaces Using NumPy:  

   import numpy as np  


Example string with spaces  

   text = "  Hello   World!  This is Python.  "  


Convert the string to a NumPy array of characters  

   char_array = np.array(list(text))  


Remove spaces by filtering out space characters  

   cleaned_array = char_array[char_array != ' ']  


Convert the array back to a string  

   cleaned_text = ''.join(cleaned_array)  
   print(cleaned_text)  


Explanation:  

  • ‘np.array(list(text))` converts the string into a NumPy array where each character is an element of the array.  
     
  • `char_array[char_array != ' ']` filters out all space characters from the array.  
     
  • `''.join(cleaned_array)` joins the remaining characters back into a single string.  


This method is more advanced & is used when you are already working with NumPy for other tasks. For simple string manipulation, the previous methods (`split()`, `strip()`, & regex) are usually more straightforward.  

Remove Spaces from a String in Python Using isspace() Method

The isspace() method checks if a string consists only of whitespace characters. We can use it to filter out spaces from a string.

Example

def remove_spaces(string):
    return "".join(char for char in string if not char.isspace())
text = "Python  is   amazing!"
new_text = remove_spaces(text)
print(new_text)
You can also try this code with Online Python Compiler
Run Code

 

Output:

Pythonisamazing!

 

Here, the function iterates over each character in the string and removes spaces using isspace().

Frequently Asked Questions

How do I remove all spaces from a string in Python?

You can use the replace() method to remove all spaces by replacing them with an empty string.

What is the difference between strip(), lstrip(), and rstrip()?

strip() removes spaces from both ends, lstrip() removes spaces from the left, and rstrip() removes spaces from the right.

Can I remove spaces using regular expressions?

Yes, the re module allows you to remove spaces using re.sub(r"\s+", "", text), which removes all spaces from a string.

Conclusion

In this article, we learned different ways to remove spaces from a string in Python. We explored methods like using the replace() function, split() and join(), list comprehensions, and regular expressions. Each approach offers a unique way to handle spaces depending on the specific requirements. Understanding these methods helps in efficiently processing and cleaning string data in Python.

Live masterclass