Python String strip() Method

Example

Remove spaces at the beginning and at the end of the string:

txt = ” banana “x = txt.strip()

print(“of all fruits”, x, “is my favorite”)

Python String strip() Method

Definition and Usage

The <span>strip()</span> method removes any leading and trailing whitespaces.

Leading means at the beginning of the string, trailing means at the end.

You can specify which character(s) to remove; if not, any whitespaces will be removed.

Syntax

string.strip(characters)

Parameter Values

Parameter Description
characters Optional. A set of characters to remove as leading/trailing characters

More Examples

Example

eg1

>>> submitted_username = “_!__Yo_JohnDoe!__!!”

>>> cleaned_username = submitted_username.strip(“!_”)

>>> cleaned_username

‘Yo_JohnDoe’

eg2

&gt;&gt;&gt; review = "¡¡¡Este producto es increíble!!!"&gt;&gt;&gt; review.strip("¡!")'Este producto es increíble'

eg3

&gt;&gt;&gt; filename = "   Report_2025 FINAL.pdf  "&gt;&gt;&gt; filename.strip().lower().replace(" ", "_")'report_2025_final.pdf'

eg4

&gt;&gt;&gt; data = ["  Alice ", " Bob  ", " Charlie\n", "\tDora"]&gt;&gt;&gt; cleaned_data = [name.strip() for name in data]&gt;&gt;&gt; cleaned_data['Alice', 'Bob', 'Charlie', 'Dora']

Compare <span><span>.strip()</span></span> With Other Python Strip Methods

Python provides several string methods to remove unwanted characters from the beginning or end of a string. While <span><span>.strip()</span></span> removes any specified characters from both ends, <span><span>.lstrip()</span></span> and <span><span>.rstrip()</span></span> allow for targeted character removal on a single side. Additionally, <span><span>.removeprefix()</span></span> and <span><span>.removesuffix()</span></span> remove exact substrings from the beginning or end of the string, respectively.

https://realpython.com/python-strip/

Leave a Comment