Summary: In this tutorial, we will learn three different ways to remove extra leading and trailing white spaces from a string in Python.

In Python, raw inputs are recorded as strings by default. Therefore, it becomes very important to trim any additional white spaces from input strings, otherwise, later typecasting them into other data types (such as integer) may result into an error.

There are three easy ways to remove extra white spaces from a string in Python:

  1. Using str.strip()
  2. Using str.rstrip() and str.lstrip()
  3. Using str.replace()

Let’s see an example of each of the methods.

Method 1: Using str.strip()

The inbuilt str.strip() method in Python returns a new string after trimimg both leading and trailing whitespaces from a the given string.

>>> string = '  Pencil Programmer  '
>>> print(string)
  Pencil Programmer  
>>> print(string.strip())
Pencil Programmer

Method 2: Using str.lstrip() and str.rstrip()

Alternative to str.strip(), we can use str.lstrip() and str.rstrip() methods to remove extra whitespaces from the string.

The str.lstrip() method in Python removes the leading whitespaces while the str.rstrip() method removes the trailing whitespaces from the string.

>>> string = '  Python Programming  '
>>> print(string)
  Python Programming  
>>> string = string.lstrip()
>>> string = string.rstrip()
>>> print(string)
Python Programming

Method 3: Using str.replace()

Another way to get rid of the extra spaces is by using the str.replace(old, new) method in Python.

If we use str.replace(' ', '') on the string object, it will replace all the white spaces with the null string.

>>> string = '  547932  '
>>> string = string.replace(' ', '')
>>> print(string)
547932

This method alogn with leading and trailing spaces will aslo remove the spaces between any two words in the given string. Hence, we should use this method for only single word string.

Leave a Reply