How to remove all trailing whitespace of string in Python?


Any character or group of characters that depicts horizontal or vertical space is known as whitespace. A whitespace character usually takes up space on a page even though it does not correspond to any visible mark when it is rendered.

Pressing the spacebar will allow you to enter a whitespace character. On many keyboards, the Tab key can also be used to enter horizontal whitespace, although the length of the space may vary.

Any spaces or tabs that follow the final non-whitespace character on the line until the newline are considered trailing whitespace.

Whitespace in Python

Whitespace is a type of character that is used for spacing and has the appearance of being empty. It refers to tabs and spaces in the context of Python. Python code is indented using white space and tabs.

Several methods, such as strip(), rstrip(), slicing, and regular expressions, among others, can be used to remove all trailing whitespace from a string in Python.

Using the strip() method

You can remove all trailing whitespace from a string in Python by using the strip() method. The strip() method removes any leading or trailing whitespace characters (including spaces, tabs, and newlines) from a string.

Example

In the following example, the strip() method is called on the my_string variable, which removes all leading and trailing whitespace characters. The resulting string is assigned to the stripped_string variable, which is then printed to the console.

my_string = "foo bar "
stripped_string = my_string.strip()
print(stripped_string)

Output

foo bar

Using rstrip() method

If you only want to remove trailing whitespace characters, you can use the rstrip() method instead:

Example

my_string = "foo baz "
stripped_string = my_string.rstrip()
print(stripped_string)

Output

foo baz

Using slicing methods

Another alternative is to use slicing to remove trailing whitespace characters. Slicing allows you to select a specific portion of a string by specifying its start and end indices. If you don't specify the start index, Python assumes it to be 0 (the beginning of the string). If you don't specify the end index, Python assumes it to be the length of the string.

In this example, we're using slicing to remove the trailing whitespace characters. The len(my_string)-my_string[::-1].index(' ') expression calculates the index of the last whitespace character in the string (starting from the end of the string). We then slice the string from the beginning to this index (excluding the whitespace character) using the [:len(my_string)-my_string[::-1].index(' ')] notation. Finally, we call the rstrip() method to remove any remaining whitespace characters.

Note that this method only works if the trailing whitespace characters are spaces. If there are other whitespace characters, such as tabs or newlines, you should use the strip() method or a regular expression to remove them.

Here's an example of using slicing to remove trailing whitespace characters −

Example

my_string = "foobar baz "
stripped_string = my_string[:len(my_string)-my_string[::-1].index('')].rstrip()
print(stripped_string)

Output

foobar baz

Using regex methods

Another approach to removing trailing whitespace characters is to use regular expressions. Regular expressions provide a powerful way to match and manipulate text patterns in Python.

In this example, we're using the re.sub() function to substitute (replace) any trailing whitespace characters with an empty string. The regular expression r'\s+$' matches one or more whitespace characters (\s+) at the end of the string ($). The re.sub() function replaces this pattern with an empty string, effectively removing the trailing whitespace characters.

Note that the r prefix in the regular expression string indicates a raw string, which allows backslashes to be used without being interpreted as escape characters.

Using regular expressions provides more flexibility and power than the other methods, as you can customize the pattern to match specific types of whitespace characters, or to exclude certain characters from being removed. However, regular expressions can be more complex and harder to understand than the other methods, so it's important to use them judiciously.

Here's an example of using regular expressions to remove trailing whitespace characters −

Example

import re
my_string = " foobar qux "
stripped_string = re.sub(r'\s+$', '', my_string)
print(stripped_string)

Output

foobar qux

We have seen how trailing whitespaces in a string are removed in Python using different methods and code examples. In the first one, we have used the strip() method, in the second, we have used the rstrip() method; in the third, we have used slicing; and in the last method, we have used regular expressions to remove trailing whitespace characters from a string in Python.

Updated on: 02-May-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements