How to Remove Whitespace from a String in Python?

Linda Hamilton
Release: 2024-10-26 01:37:27
Original
667 people have browsed it

How to Remove Whitespace from a String in Python?

Trimming Whitespace in Python

Question: How can whitespace (spaces and tabs) be removed from a string in Python?

Answer:

There are several methods available in Python for trimming whitespace from strings:

1. str.strip()

The str.strip() method removes whitespace from both the left and right sides of a string. For example:

<code class="python">s = "  \t a string example\t  "
s = s.strip()
print(s)  # Output: "a string example"</code>
Copy after login

2. str.rstrip()

The str.rstrip() method removes whitespace only from the right side of a string:

<code class="python">s = s.rstrip()
print(s)  # Output: "a string example"</code>
Copy after login

3. str.lstrip()

The str.lstrip() method removes whitespace only from the left side of a string:

<code class="python">s = s.lstrip()
print(s)  # Output: "a string example  "</code>
Copy after login

4. str.strip(chars)

You can also specify a specific set of characters to strip using the str.strip(chars) method:

<code class="python">s = s.strip(' \t\n\r')
print(s)  # Output: "astringexample"</code>
Copy after login

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

5. re.sub

Additionally, you can use the regular expression module (re) to remove whitespace from a string:

<code class="python">import re
print(re.sub('[\s+]', '', s))  # Output: "astringexample"</code>
Copy after login

This regular expression will substitute any amount of whitespace with an empty string, effectively trimming the whitespace.

The above is the detailed content of How to Remove Whitespace from a String 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!