strip() method removes characters from both left and right based on the argument (a string specifying the set of characters to be removed).
The syntax of the
strip() method is:
- chars (optional) - a string specifying the set of characters to be removed from the left and right part of the string.
If the chars argument is not provided, all leading and trailing whitespaces are removed from the string.
Return Value from the strip() method
strip() returns a copy of the string with both leading and trailing characters stripped.
Working of the strip() method
- When the character of the string in the left mismatches with all the characters in the
charsargument, it stops removing the leading characters.
- Similarly, when the character of the string in the right mismatches with all the characters in the
charsargument, it stops removing the trailing characters.
Example: Working of the strip() method
string = ' xoxo love xoxo ' # Leading and trailing whitespaces are removed print(string.strip()) # All <whitespace>,x,o,e characters in the left # and right of string are removed print(string.strip(' xoe')) # Argument doesn't contain space # No characters are removed. print(string.strip('stx')) string = 'android is awesome' print(string.strip('an'))
xoxo love xoxo lov xoxo love xoxo droid is awesome
Here, we can see that the first expression
string.strip() without any arguments removed the whitespaces from the left and right of
string.strip(' xoe') removed all whitespace,
e that lead or trailed the string.
string has whitespace at the beginning and end, the expression
string.strip('stx') does not change the string.
x is not removed since it is at the middle of the string (whitespaces lead and trail the string)
an leading the string.