Introduction
In Python, the strip() is a built-in method, this method returns a copy of the string with the leading and trailing character both removed (according to arguments passed).
Syntax
Parameter
In this method, there is only a single argument that it takes and it is also optional.
- chars: It is a string that signifies the character to be removed from the string.
NOTE: If the argument is not specified then this method will remove all leading and trailing whitespaces from the string.
Return Value
This method returns a copy of the string containing the leading and trailing characters from the string that are removed.
Purpose of strip() method
In Python, the strip() method comes in handy when the developer is required to remove characters or whitespaces from a string.
Let us have a clear look at the uses of this method.
- This method helps in removing the characters from the beginning or end of a string of characters specified as the argument to the strip() method.
- If the string does not contain any whitespace and the characters argument is also not specified, then the string is returned with no changes.
- If the string has some whitespaces and no character arguments are passed, then the string is returned e=with whitespaces remove from it.
- It is also good practice to remove the whitespaces from the beginning and end of the string.
Examples
Code 1
Output
Code 2
Output
Explanation
- The first step is we create a string named s1. This string stores ‘ihi hey ihi’.
- And then we will create a new string named s2 which stores ‘hi’.
- This string s2 will be stripped of s1, by using the strip() method and passing s2 as the argument.
- Now python interpreter will trace the string s2 in the string s1 from the list and will remove it if present.
- If not present then the python interpreter will stop tracing and will start again from the right.
- Again if not found then it will return the string with changes made.
Practical Application
We are given a string with the occurrences of ‘the’, we have to use the python strip() method to remove those occurrences along with whitespaces if present.
Code
Output