Python Remove Spaces from String With Examples

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 tnrtHi 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 tnrtHi 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(" ", "")
'HelloWorldFromPankajtnrtHiThere'

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

Reference: StackOverflow Question

By admin

Leave a Reply

%d bloggers like this: