Python String strip() Method

The strip() method returns a copy of the string by removing both the leading and the trailing characters. By default, it removes leading whitespaces if no argument passed.

Syntax:

str.strip(characters)

Parameters:

characters: (Optional) a string to be removed from the starting and ending of a string. By default, it removes all leading and trailing whitespaces if no argument is specified.

Return Value:

Returns a string.

The following examples demonstrates the strip() method.

Example: strip()
>>> mystr = '     Hello World     '
>>> mystr.strip() 
'Hello World'
>>> mystr = '''
Python is 
a programming language'''
>>> mystr.strip()  
'Python is \na programming language'
>>> mystr = '----Hello World----'
>>> mystr.strip('-')  
'Hello World'

You can specify one or more characters as a string to be removed from the string in any order, as shown below.

Example: strip()
>>> '#$2Hello World#$2'.strip('$2#')
'Hello World'
>>> '#$-2Hello World#$2'.strip('$2#')
'-2Hello World'
>>> 'www.tutorialsteacher.com/'.strip('/w.') 
'www.tutorialsteacher.com'
>>> 'ābcā'.strip('ā') # remove Unicode char
'bc'

In the above example, '#$2Hello World#$2'.strip('$2#') removes leading and trailing chars'$', '2', or '#' if appears in any order. However, #$-2Hello World#$2'.strip('$2#') removes only leading '#' and '$' because '-' is not specified to be removed, so it stops there and considers it as a word.