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.
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.
stripedString = "<some-string>".strip(<chars>)
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
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.
The following example illustrates the working of string function with different strings and different arguments.
#Removing Trailing White Spaces
string1 = " Hello, How are you? Loving Python? "
#Removing two chracters from the
#Leading and Trailing Edges
string2 = "gghg Hello Hi!ghghghgh"
#Spaces also needs to be explicitally defined
#If need to be removed along with
string3 = "gghg Hello Hi!ghghghgh"
#H and h are different
string4 = "helloYello!Hello"
#Observe the Difference of Removing
#the ! mark
string5 = "helloYelloHello"
#Nothing will be removed on chracters mismatch
#In The Start or End
string6 = "yoHellooy"
#Removed only from one side
string7 = "yoHelloyo"
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!