Python String | strip()

strip() in-built function of Python is used to remove all the leading and trailing spaces from a string.

Syntax :

string.strip([remove])

Parameters :



remove (optional): Character or a set of characters, that needs to be removed from the string.

The function can take one or no parameter. If no parameter is passed then only the leading and trailing spaces are removed.

Return Values :

The function returns another string with both leading and trailing characters being stripped off.

  • When the removed string matches perfectly then the modified string is returned with removed characters and spaces.
  • When the remove string does not match then no modification is made to the original string.
  • The below code displays the working of strip() in various conditions.

    Code #1

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Python code to illustrate the working of strip()
    string = '   Geeks for Geeks   '
      
    # Leading spaces are removed
    print(string.strip())
      
    # Geeks is removed
    print(string.strip('   Geeks'))
      
    # Not removed since the spaces do not match
    print(string.strip('Geeks'))

    chevron_right

    
    

    Output :

    Geeks for Geeks
    for
       Geeks for Geeks   
    

     
    COde #2

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Python code to illustrate the working of strip()
    string = '@@@@Geeks for Geeks@@@@@'
      
    # Strip all '@' from beginning and ending
    print(string.strip('@'))
      
    string = 'www.Geeksforgeeks.org'
      
    # '.grow' removes 'www' and 'org' and '.'
    print(string.strip('.grow'))

    chevron_right

    
    

    Output :

    Geeks for Geeks
    Geeksforgeeks

     
    Practical Application :
    The following code shows an application of strip() in python.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Python code to check for identifiers
    def Count(string):
          
        print("Length before strip()")
        print(len(string))
          
        # Using strip() to remove white spaces
        str = string.strip()
        print("Length after removing spaces")
        return str
          
    # Driver Code    
    string = "  Geeks for Geeks   "
    print(len(Count(string)))

    chevron_right

    
    

    Output :

    Length before strip()
    17
    Length after removing spaces
    15
    


    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.