How to Strip Whitespace from Strings in Python?

Patricia Arquette
Release: 2024-10-27 15:07:01
Original
647 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!