Home > Article > Backend Development > 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>
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>
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>
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>
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>
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!