Python Tutorials

How to use Python strip() function on string

Syntax:

str.strip('characters')

'characters' is optional


Example:

str = '***Welcome to getechready***'
new_str = str.strip('*')
print(new_str)

Note: You don't have to write the same character multiple times, single time will work. Python keeps on removing the character till the time it finds the same character. It repeats the process on both side.

Output:

>>>Welcome to getechready


  • The passed argument does not necessarily should be present on both side. It can be present on either side Python will take care of it.
  • str = 'Welcome to getechready'
    new_str = str.strip('Wel') #the argument is case senstitve
    print(new_str)


    Output:

    >>>come to getechready


    Trim leading and trailing spaces :

    Mostly strip() method is used for trimming starting and ending spaces from string.

    str = '    Welcome to getechready  '   #need not be same number of spaces
    new_str = str.strip()
    print(new_str)


    Output:

    >>>Welcome to getechready


  • The order of the characters passed in the strip() method does not matter, it removes all provided characters till they are contiguous.
  • str = 'racecar'
    new_str = str.strip('rca')
    print(new_str)


    Output:

    >>>e


  • With order the number of the characters passed in the strip() method also does not matter.
  • str = 'mississippi'
    new_str = str.strip('ism')
    print(new_str)


    Output:

    >>>pp

    Note: 'ism' characters matched from the starting i.e. 'mississi' and only 'i' from 'ism' matched from the end.


  • If we pass list, strip() will throw an exception
  • str = 'getechready'
    new_str = str.strip(['get'])


    Output:

    >>>TypeError: strip arg must be None or str


    Also read: rstrip() method and lstrip() method