Home  >  Article  >  Backend Development  >  How to Strip Whitespace from Strings in Python?

How to Strip Whitespace from Strings in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 15:07:01646browse

How to Strip Whitespace from Strings in Python?

Strip Whitespace from Strings in Python

In Python, manipulating strings and removing unwanted characters is often necessary. One common task is trimming whitespace, which includes spaces and tabs, from the beginning or end of a string. This helps clean up strings and make them easier to work with.

Several options are available for trimming whitespace in Python:

For Whitespace on Both Sides:

Use the str.strip() method. This removes whitespace from both the left and right sides of the string.

<code class="python">s = "  \t example string\t  "
s = s.strip()</code>

For Whitespace on the Right Side:

Use the str.rstrip() method. This removes whitespace only from the right side of the string.

<code class="python">s = s.rstrip()</code>

For Whitespace on the Left Side:

Use the str.lstrip() method. This removes whitespace only from the left side of the string.

<code class="python">s = s.lstrip()</code>

Custom Character Removal:

You can specify specific characters to remove using these methods. For instance:

<code class="python">s = s.strip(' \t\n\r')</code>

This will remove any space, t, n, or r characters from both sides of the string.

Remove Whitespace from the Middle:

To remove whitespace from the middle of a string, you can use the re.sub function:

<code class="python">import re
print(re.sub('[\s+]', '', s))</code>

The above is the detailed content of How to Strip Whitespace from Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn