Python Remove Spaces from String

Filed Under: Python
Python Remove Spaces From String

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 checkout complete python script and more Python examples from our GitHub Repository.

Reference: StackOverflow Question


  1. Sai Vinay Palakodeti says:

    Thank you so much.

  2. Moulya says:

    hey nice one thank you helped me in my code

  3. ypll says:

    Very helpful article, Pankaj. Thank you for this

  4. Pegel says:

    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

    1. Chidhvilas says:

      You’re using **greeting.upper()** str.upper()- method returns all strings capitalized.

      Plus why use **user.capitalize()**str.capitalize()-method returns first letter of string in upper case. which you seem to have already done.

      Refer to docs for detailed description on string methods

  5. Munir says:

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

  6. Azmain Nisak says:

    This was so helpful! Thanks for putting this together! 馃檪

  7. DEEPAK says:

    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()
    see both the trailing and leading spaces have been removed

    1. pegel says:

      nvm figured it out, thanks

  8. DJ says:

    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 ‘

    What the heck? It doesn’t work!

    1. Pankaj says:

      Thanks for the feedback, I have included one-liner to point this out.

    2. NSK...NGU says:

      s = ‘your string’
      s = s.strip ()
      print (s)

      This will work

    3. Skata says:

      Use the replace.

      The strip() not work!

      string=’Hello world’
      string=string.replace(” “,””)

    4. Sarthak Dandgawhal says:

      Thank you sir, it was very helpful for me.馃檹

  9. Valentino says:

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


Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content