Python String strip()

The strip() method returns a copy of the string by removing both the leading and the trailing characters (based on the string argument passed).

The 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:

string.strip([chars])

strip() Parameters

  • 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 chars argument, it stops removing the leading characters.
  • Similarly, when the character of the string in the right mismatches with all the characters in the chars argument, 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'))

Output

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.

string.strip(' xoe') removed all whitespace,x, o, and e that lead or trailed the string.

Since 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)

string.strip('an') removed an leading the string.