Summary: In this programming example, you will learn different ways to remove whitespaces from a string in Python.

Use strip() to remove the Leading and Trailing Whitespace

Call the strip() method on the string object to remove the leading and trailing whitespace from the string.

>>> string = '  pencil programmer  '
>>> string.strip()
'pencil programmer'

Use lstrip() to remove the Leading Whitespace

Call the lstrip() method on the string object to remove only the leading whitespace from the given string.

>>> string = '  programming  '
>>> string.lstrip()
'programming  '

Use rstrip() to remove the Trailing Whitespace

Call the rstrip() on the string object to remove the whitespaces that are on the right side of the string.

>>> string = '  Python  '
>>> string.rstrip()
'  Python'

Use split() to remove Duplicate Whitespace

Call the split() method on the string and pass the result to the join() method to remove duplicate whitespaces.

>>> string = '  I   am a   Student  '
>>> result = string.split()
>>> ' '.join(result)
'I am a Student'

Use replace() to remove All Whitespace

Use the replace() method, if you want to remove all whitespaces from the given string.

>>> string = '  Pencil Programmer  '
>>> string.replace(' ', '')

Use Regex to remove Whitespace

You can also remove whitespace using the regular expression in Python.

Pass the string object along with the regex expression to the re.sub() function as shown in the following example.

import re

string = ' Hi, Its me   AK  '

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


Remove leading and trailing whilespaces:
'Hi, Its me   AK'

Remove leading whilespaces:
'Hi, Its me   AK  '
Remove trailing whitespaces:
' Hi, Its me   AK'

Remove all whitespaces:
Post author avatar

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply