How To Trim Whitespace from a String in Python: Easy Methods

How To Trim Whitespace from a String in Python

Python delivers three methods that you can utilize to trim whitespace from a string and return a new string object. The string strip methods can trim showing whitespace, trailing whitespace, or both.

Whitespace contains all Unicode whitespace characters, such ascarriage returns (\r),spaces, tabs (\t) and newlines (\n). The Python str() class has the following ways that you can use to trim whitespace from a string:

  • rstrip([chars]): Trims characters from the right side of a string. When chars is omitted or None, returns a new string with all trailing whitespace emptied.
  • strip([chars]): Trims symbols from both ends of a string. When chars is omitted or None, returns a new string with all showing and trailing whitespace removed.
  • lstrip([chars]): Trims characters from the left side of a string. When chars is omitted or None, returns a new string with all leading whitespace cleared.

Trimming Whitespace from a String Using Strip Methods

The following instance demonstrates how to trim trailing spaces, leading spaces, and both leading and trailing spaces from a string:

The output is:

The following instance demonstrates how to use the same strip methods to trim numerous whitespace characters from a string:

The output is:

The output indicates that using the strip methods with the chars statement omitted removes only the leading and trailing space, newline, and tab characters from the string. Any whitespace that’s not at the very start or end of the string isn’t removed.

Trimming a Specific Whitespace Character from a String Using Strip Methods

You can even remove only a character or characters from the start and end of a string by determining the chars argument. The following instance demonstrates how to trim only the leading newline character from a string:

The output is:

The output indicates that the lstrip() method removes the leading newline character but doesn’t clear the leading spaces from the string.

Note that the strip procedure only removes specific characters when they’re the outermost leading and trailing characters. For instance, you can’t use rstrip() to remove only the trailing tab character from s3 = ‘\n sammy\n shark\t ‘ because of the spaces after \t.

Conclusion

In this article, you operated the strip(), rstrip(), and lstrip() techniques to trim leading and trailing whitespace from strings.

Eram N.
Author: Eram N.

I have been serving web content with my passionate writing skills since 2020. My skills have benefited clients from 20 countries, resulting in 10x audience interactions, improved readability, and SEO-friendly content.

Eram N.
I have been serving web content with my passionate writing skills since 2020. My skills have benefited clients from 20 countries, resulting in 10x audience interactions, improved readability, and SEO-friendly content.