Python: Remove whitespace from the end of string

In this article, we will discuss two different ways to remove trailing whitespace from a string i.e. removing whitespace from the end of s string. These two ways are,

  • Using rstrip() function
  • Using regex module’s rsub() function

Let’s see both the techniques one by one,

Remove whitespace from the end of string using rstrip()

In Python, string provides a function rstrip(). It returns a copy of the calling string object after removing all the whitespace characters from the end of string. Basically it strips the whitespace characters from the right of string i.e. end of the string. For example,

sample_str = "  \t This  is  a Sample   String    \t\n   "

# Removing trailing whitespace from a string
sample_str = sample_str.rstrip()

print(f"'{sample_str}'")

Output:

'        This  is  a Sample   String'

It removed the trailing whitespace from the given string.

Remove whitespace from the end of string using regex

In Python, the regex module provides a function sub(). It replaces the contents of a string based on a given matching regex pattern. Its signature is like this,

sub(pattern, replacement_str, original_str)

We can use this to remove trailing whitespace from a string. For this we need to pass a regex pattern that matches one or more whitespace characters in the ending of string like r”\s+$”. Also, as a replacement string we need to pass the empty string. For example,

import re

sample_str = "  \t This  is  a Sample   String    \t\n   "

# Removing trailing whitespace from a string
sample_str = re.sub(r"\s+$", "", sample_str)

print(f"'{sample_str}'")

Output:

'        This  is  a Sample   String'

It removed the trailing whitespace from the given string.

Summary:

We learned about two ways to remove trailing whitespace from a string in python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top