The Python String strip() Method
strip() method in Python removes the leading and trailing characters from a string and returns a new string. The characters that are to stripped are based on a string of characters passed into the
In this tutorial, we will learn how to use the
strip() method in Python using examples to understand its behaviour.
The strip() Syntax
strip() method is passed after a string using a
. (dot). Inside the
() (parenthesis) of the method, an optional set of characters to look for at the beginning and end of the string can be included – if nothing is passed Python will remove all white spaces from the start and end of the string.
Remove All Leading and Trailing Whitespaces in a String
strip() is useful if you need to remove all the space characters at the beginning and of a string. To do this don't pass anything inside the parenthesis of
string = ' hello ' stripped = string.strip() print(stripped)
You could achieve the same as above with a small bit of regex, but with
strip() it is cleaner.
Removing Specific Characters from Start and End of a String
To remove specific characters from the end of a string pass them inside the parenthesis of
strip(). So long as at least one of the supplied characters is next in from the end as
strip() moves sequentially inward it will be removed. Let's try this out with the string
hannah to remove the characters
a from each end of the string.
string = 'hannah' stripped = string.strip('ahw') print(stripped)
Let's see how the same code as above works except this time with a character after the first
h which is not included in the
string = 'h!annah' stripped = string.strip('ahw') print(stripped)
You now know how to use the
strip() method and how it behaves when removing characters from a string.