Home  >  Article  >  Backend Development  >  How can I efficiently remove unwanted whitespace from a string in Python?

How can I efficiently remove unwanted whitespace from a string in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 13:24:30190browse

How can I efficiently remove unwanted whitespace from a string in Python?

Trimming Whitespace with Python

When working with strings, it's often necessary to remove unwanted whitespace characters, such as spaces and tabs. Python provides several built-in functions to help you achieve this.

str.strip()

The str.strip() function removes whitespace characters (spaces, tabs, newlines, and carriage returns) from both sides of a string. For example:

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

str.rstrip()

The str.rstrip() function removes whitespace characters from the right side of a string. For example:

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

str.lstrip()

The str.lstrip() function removes whitespace characters from the left side of a string. For example:

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

Custom Character Removal

You can specify custom characters to remove using the optional argument in the strip(), rstrip(), and lstrip() functions. For example:

<code class="python">s = " \t\n example string\t  "
s = s.strip(' \t\n')
print(s)  # Output: "example string"</code>

Regex for Whitespace Removal

If you need to remove whitespace characters from the middle of a string, you can use regular expressions. For example:

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

The above is the detailed content of How can I efficiently remove unwanted whitespace from a string 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