Sling Academy
Home/Python/Python: Remove leading/trailing whitespace from a string

Python: Remove leading/trailing whitespace from a string

Last updated: May 24, 2023

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.

Next Article: Python: 5 Ways to Reverse a String

Previous Article: Python: 7 Ways to Find the Length of a String

Series: Working with Strings in Python

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types