Python String strip() Method Tutorial

Python String Strip() Method

This is a detailed tutorial of the Python String strip() method. Learn to remove the leading and trailing characters from a string as per another string.

Python String strip()

The Python String strip() method simply removes the leading and trailing characters from a string on which it is applied according to another string which has been provided to this method as an argument. Only the characters that you have specified in the argument string will be removed from the leading & trailing edges (left and right sides) of the string.

Syntax

strip() Parameters

The strip() method that can be applied on any of the String takes only one argument and it is a string type argument. This string type argument is actually the set of characters that are needed to removed from the leading and trailing edges of the string.

Note. This is an optional parameter. If it will not be provided, this method will only remove the leading the trailing empty white spaces from the string on which it is applied.

You have to specify the different characters that are meant to be removed from the left and right-hand side of the string as a single string argument. For example, if you wanted the two characters h and x to be removed from a string, you must provide "hx" as the argument. Providing the same characters multiple times here will have the same effect as providing it one time.

strip() Return Value

The return value of the method strip() is obviously a new string with the characters in the argument removed from the leading and trailing edges. This method continues removing the characters from the string start and end unless or until it founds characters in the string that do not match with the characters in the argument string.

The left and right-hand side removal of characters are independent of each other. It means that it will continue removing the characters from either side of the string as long as they keep on matching with the argument string characters irrespective of what’s happening on the other side of the string.

Example

The following example illustrates the working of string function with different strings and different arguments.

Output.

Python String Strip() Function Example

I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.

And do not forget to subscribe to WTMatter!

Subscribe To WTMatter!

Receive updates of our latest articles via email. Enter your email address below to get started.

Leave a Reply

Your email address will not be published. Required fields are marked *