Python String strip() Method
The strip()
method is used to remove leading and trailing characters from a string. By default, it removes whitespace characters such as spaces, tabs, and newlines.
Syntax
string.strip([chars])
Parameter
chars
(Optional): A string specifying a set of characters to be removed. If omitted, it removes whitespace characters (spaces, tabs, newlines) from both ends.
Return Value
Returns a new string with specified leading and trailing characters removed. It doesn’t modify the original string.
Examples
Basic Usage (Removing Whitespaces)
text = " Python is awesome "
stripped_text = text.strip()
print(stripped_text) # Output: Python is awesome
Removing Specific Characters
text = "###Python is awesome###"
stripped_text = text.strip("#")
print(stripped_text) # Output: Python is awesome
Removing Multiple Characters
text = "abcPython is awesome!cba"
stripped_text = text.strip("abc")
print(stripped_text) # Output: Python is awesome!
In this example, the strip()
method is not removing the exact substring "abc"
from the start and end. Instead, it removes any combination of the characters "a"
, "b"
, or "c"
from both the beginning and the end of the string.
Let’s take a look at another code example:
text = "banana"
stripped_text = text.strip("ba")
print(stripped_text) # Output: nan
The strip()
method only removes characters from the beginning and the end. Characters in the middle are not affected.
If you need to remove characters only from the beginning of a string, use the lstrip()
method.
Similarly, if you need to remove characters only from the end of a string, use the rstrip()
method.