What is the string.strip method in python?
The strip method will remove a set of leading and trailing characters in a string and return a new string.
Syntax
string.strip([chars_to_remove])
The strip() method
The strip method will first loop through all the characters from the start of the string and then loop from the end of the string.
On looping, the current character of the string is present in the passed chars_to_remove is checked.
-
If the current character is present in the
chars_to_removethen that character will be removed. -
If the current character is not present, then the looping is stopped.
Parameter
chars - set of characters to be removed from the string’s leading position (starting) and trailing (end).
It is an optional argument. By default, the leading and trailing spaces are removed.
Return value
A new string in which the passed set of characters are removed.
Code
Example 1
string = " space at start and end is removed ";
string.strip();
Explanation 1
In the code above, we have a string with whitespace at the start and end of the string.
When we call the strip method without any argument, the space at the string’s beginning and end is removed.
Example 2
string = "sun raises";
string.strip("se"); #pace set
Explanation 2
In the code above, we have a sun raises string and called the strip('s') method.
The strip method will first loop the string space set from the beginning
-
First char -
sis present in the passed argument, so it is removed from the string. Now the result string isun raises. -
Second char -
uis not present in the passed argument so looping is stopped and the stringun raisesis returned.
The strip method will then loop the string space set from the end
-
Last char -
sis present in the passed argument so it is removed from the string. Now the result string isun raise. -
Second last char -
eis present in the passed argument so it is removed from the string. Now the result string isun rais. -
Third last char -
sis present in the passed argument so it is removed from the string. Now the result string isun rai. -
Fourth last char -
iis not present in the passed argument, so looping is stopped and the stringun raiis returned.
Complete example
string = " space at start and end is removed ";print(string.strip());string = "sun raises";print(string.strip("se")); #un rai