Home > Article > Backend Development > Here are a few title options, tailored to the question-and-answer format: **Focus on Specific Techniques:** * **How to Trim Whitespace in Python: strip(), rstrip(), lstrip()** * **Removing Whitesp
Trimming Whitespace in Python
To remove whitespace characters (spaces and tabs) from a string in Python, several options are available:
For whitespaces on both sides:
<code class="python">s = " \t example string\t " s = s.strip()</code>
For whitespaces on the right side:
<code class="python">s = s.rstrip()</code>
For whitespaces on the left side:
<code class="python">s = s.lstrip()</code>
Stripping Specific Characters:
You can specify which characters to remove from the string by passing them as an argument to the strip() functions:
<code class="python">s = s.strip(' \t\n\r')</code>
This will remove any spaces, tabs, newlines, or carriage returns from both sides of the string.
Removing Whitespaces from the Middle of a String:
To remove whitespaces from the middle of a string, you can use regular expressions:
<code class="python">import re print(re.sub('[\s+]', '', s))</code>
This will remove all consecutive sequences of whitespace characters from the string.
The above is the detailed content of Here are a few title options, tailored to the question-and-answer format: **Focus on Specific Techniques:** * **How to Trim Whitespace in Python: strip(), rstrip(), lstrip()** * **Removing Whitesp. For more information, please follow other related articles on the PHP Chinese website!