// Tutorial //

Python Remove Spaces from String

Published on August 3, 2022
Default avatar
By Pankaj
Developer and author at DigitalOcean.
Python Remove Spaces from String

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

There are various ways to remove spaces from a string in Python. This tutorial is aimed to provide a short example of various functions we can use to remove whitespaces from a string.

Python Remove Spaces from String

Python String is immutable, so we can’t change its value. Any function that manipulates string value returns a new string, and we have to explicitly assign it to the string. Otherwise, the string value won’t change. Let’s say we have an example string defined as:

s = '  Hello  World   From Pankaj \t\n\r\tHi There  '

This string has different types of whitespaces as well as newline characters. Let’s have a look at different functions to remove spaces.


Python String strip() function will remove leading and trailing whitespaces.

>>> s.strip()
'Hello  World   From Pankaj \t\n\r\tHi There'

If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.


We can use replace() to remove all the whitespaces from the string. This function will remove whitespaces between words too.

>>> s.replace(" ", "")

join() with split()

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

>>> " ".join(s.split())
'Hello World From Pankaj Hi There'


If you want to get rid of all the whitespaces as well as newline characters, you can use string translate() function.

>>> import string
>>> s.translate({ord(c): None for c in string.whitespace})

python remove spaces from string

Python Remove Whitespaces from String using Regex

We can also use a regular expression to match whitespace and remove them using re.sub() function.

import re

s = '  Hello  World   From Pankaj \t\n\r\tHi There  '

print('Remove all spaces using RegEx:\n', re.sub(r"\s+", "", s), sep='')  # \s matches all white spaces
print('Remove leading spaces using RegEx:\n', re.sub(r"^\s+", "", s), sep='')  # ^ matches start
print('Remove trailing spaces using RegEx:\n', re.sub(r"\s+$", "", s), sep='')  # $ matches end
print('Remove leading and trailing spaces using RegEx:\n', re.sub(r"^\s+|\s+$", "", s), sep='')  # | for OR condition


Remove all spaces using RegEx:
Remove leading spaces using RegEx:
Hello  World   From Pankaj 	
	Hi There  
Remove trailing spaces using RegEx:
  Hello  World   From Pankaj 	
	Hi There
Remove leading and trailing spaces using RegEx:
Hello  World   From Pankaj 	
	Hi There

python remove whitespaces from string using regular expressions

You can check out the complete Python script and more Python examples from our GitHub Repository.

Reference: StackOverflow Question

Want to deploy your application quickly? Try Cloudways, the #1 managed hosting provider for small-to-medium businesses, agencies, and developers - for free. DigitalOcean and Cloudways together will give you a reliable, scalable, and hassle-free managed hosting experience with anytime support that makes all your hosting worries a thing of the past. Start with $100 in free credits!

Learn more here

About the authors
Default avatar


Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?

Thank you so much.

- Sai Vinay Palakodeti

    hey nice one thank you helped me in my code

    - Moulya

      Very helpful article, Pankaj. Thank you for this

      - ypll

        greeting= “Hello” user= “Guy” message= “welcome to the thunderdome Friend” print(greeting.upper(), user.capitalize(), message.strip( ).lower() ) ive also tried print(greeting.upper(), user.capitalize(), message.replace(" ", " ").lower() ) goal is to lowercase friend and get rid of white space. when I run the .py file through cmd it just returns HELLO Guy welcome to the thunderdome friend no matter what I seem to try

        - Pegel

          the replace function helped me where i was thinking of a more complex solution. So thank you

          - Munir

            This was so helpful! Thanks for putting this together! :)

            - Azmain Nisak

              let me explain you with an simple example s= (" PYTHON “) #so here i am using both and leading and trailing spaces output= s.strip(” “) # in between double quotes i am using space as i have used space before and after PYTHON print(output) # you will get output as “PYTHON” … another example while using idle --------------------------------------- >>> s= (” python ") >>> s.strip() ‘python’ >>> see both the trailing and leading spaces have been removed

              - DEEPAK

                You really need to point out that the functions create and return a new string, they do not change the original. Yes, strings being immutable is a foundational Python concept but someone who’s looking for this level of help is probably very new to Python. It can be incredibly frustrating for a beginner to find a page like this and do: s = " My string with leading/trailing spaces ’ s.strip() print(s) What the heck? It doesn’t work!

                - DJ

                  I don’t see anymore the date things were published. Why is it removed? Regards

                  - Valentino