Python Remove Spaces from String

Filed Under: Python

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.

strip()

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.

replace()

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


>>> s.replace(" ", "")
'HelloWorldFromPankaj\t\n\r\tHiThere'

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'

translate()

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})
'HelloWorldFromPankajHiThere'

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

Output:


Remove all spaces using RegEx:
HelloWorldFromPankajHiThere
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

Comments

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

  2. 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 ‘
    s.strip()
    print(s)

    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. Valentino says:

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

    Regards

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages