Python: Remove leading/trailing whitespace from a string

Updated: May 24, 2023 By: Goodman Post a comment

This concise, straightforward article will show you a couple of different ways to trim leading and trailing whitespace from a given string in Python.

Overview

You can skip this section and move on to the next one if you’re in a hurry and want to see code examples as soon as possible. If it’s not urgent then try to endure this part as it may be helpful for you in some way.

Leading whitespace refers to any whitespace characters (spaces, tabs, etc.) that appear at the beginning of a string. Trailing whitespace, on the other hand, refers to whitespace characters that appear at the end of a string.

Removing leading and trailing whitespace is often necessary for several reasons:

  • Data cleanliness and consistency: Leading or trailing whitespace in strings can lead to inconsistencies and errors when comparing or processing data. Removing whitespace ensures that the data is in a standardized and consistent format.
  • Input validation: When receiving user input, it’s important to remove leading and trailing whitespace to ensure that the input doesn’t contain any unintended spaces or formatting issues that could interfere with further processing or cause incorrect results.
  • String comparison: When comparing strings, leading and trailing whitespace can affect the results. Removing whitespace ensures accurate string comparison, as the content of the string is compared rather than any extra whitespace.
  • Formatting and display: In certain situations, leading or trailing whitespace may affect the desired formatting or visual appearance of text. Removing the whitespace ensures that the text is correctly formatted and presented as intended.

Ways to remove leading/trailing whitespace

Using strip(), lstrip(), or strip() method

The str.strip() method removes both leading and trailing whitespace from a string.

Example:

text = "  Sling Academy   "
trimmed = text.strip()

print(f"The original text is: '{text}'")
print(f"The trimmed text is: '{trimmed}'")

Output:

The original text is: '  Sling Academy   '
The trimmed text is: 'Sling Academy'

In cases where you only want to remove leading or trailing whitespace from a string, just use the str.lstrip() or str.rstrip() method, respectively.

Example:

text = "  To the moon!    "

left_stripped = text.lstrip()
right_stripped = text.rstrip()

print(f"The original text is: '{text}'")
print(f"The left-stripped text is: '{left_stripped}'")
print(f"The right-stripped text is: '{right_stripped}'")

Output:

The original text is: '  To the moon!    '
The left-stripped text is: 'To the moon!    '
The right-stripped text is: '  To the moon!'

Using regular expressions

The re.sub() function can be used to remove leading and trailing whitespace from a given string by using the following regular expression pattern:

r'^\s+|\s+$'

Example:

import re
text = "     Welcome to Sling Academy!     "
trimmed = re.sub(r'^\s+|\s+$', '', text)

print(f"Original: '{text}'")
print(f"Trimmed: '{trimmed}'")

Output:

Original: '     Welcome to Sling Academy!     '
Trimmed: 'Welcome to Sling Academy!'

Regular expressions are powerful and flexible, but the trade-off is that you have to write down the pattern for your use case. It isn’t always a simple task.

Using the removeprefix() and removesuffix() methods

The removeprefix() and removesuffix() methods are new in Python 3.9, and they can be used to remove leading and trailing whitespace. However, they only remove the exact prefix or suffix that matches the argument. This is useful if you don’t want to remove all leading or trailing whitespace characters. Otherwise, it would be better to use strip(), lstrip(), or rstrip().

Example:

text = "    Git gud in playing games.    "

# remove 1 leading whitespace character
left_stripped_text = text.removeprefix(" ")

# remove 3 trailing whitespace characters
right_stripped_text = text.removesuffix("   ")

print(f"Original text: '{text}'")
print(f"Left-stripped text: '{left_stripped_text}'")
print(f"Right-stripped text: '{right_stripped_text}'")

Output:

Original text: '    Git gud in playing games.    '
Left-stripped text: '   Git gud in playing games.    '
Right-stripped text: '    Git gud in playing games. '

When looking at the output, you could see that there is still some left and right whitespace remains.

Afterword

You’ve learned more than one technique to trim a string in Python. In my opinion, the first approach is simple, efficient, and should be used in most times. However, in some specific situations, the two later ones might become good saviors.