Python Strip() Method With Examples

Posted in /   /  

Python Strip() Method With Examples
vinaykhatri

Vinay Khatri
Last updated on March 29, 2024

    In Python, the string data type supports a strip() method which is capable of removing the initial and ending space or characters from a string. By default, the strip() method removes the leading and trailing spaces from a string, but it can also remove specified characters.

    Pythonn strip() syntax

    # to remove extra initial and ending spaces
    string.strip()
    # to remove extra initial and ending characters.
    string.strip(character)

    strip() method can remove characters from the left and right sides of the string based on the passed argument.

    Example

    string = "    TechGeekBuzz    "
    
    # without strip() method
    print(string)
    
    # with strip() method
    print(string.strip())

    Output

        TechGeekBuzz 
    TechGeekBuzz

    Behind the Code

    In the above example, the string identifier has a value "    TechGeekBuzz    " , and there are 4 spaces at the beginning and end of the string. Python reads spaces as normal characters and prints them. The strip() method removes those spaces and prints the text. The strip() method only deals with the initial and ending spaces and characters of a string. It does not remove the extra spaces between the characters.

    Example

    string = "    Tech    Geek    Buzz    "
    
    # without strip() method
    print(string)
    
    # with strip() method
    print(string.strip())

    Output

        Tech    Geek    Buzz 
    Tech    Geek    Buzz

    In this example, the strip() method only removes the spaces that were at the beginning and end of the string .

    strip(char) Parameter

    We can pass a single character or string in the strip() method, and this will remove that character or string if it is present at the beginning and/or end of the string.

    Syntax

    string.strip(char)

    Example

    string = "heading Tech Geek Buzz heading"
    
    # it will remove the heading from the end and beginning
    print(string.strip("heading"))

    Output

     Tech Geek Buzz

    Conclusion

    Following are the key points to keep in mind while working with the Python strip() method:

    • By default, the strip() method removes the initial and ending spaces.
    • strip() method can accept a character and remove that character if present at the beginning and end of the string.

    We hope that this tutorial has helped you to develop a sound understanding of the Python strip() method. However, if you have any queries related to the Python Strip method, leave them in the comments section below.

    People are also reading:

    Leave a Comment on this Post

    0 Comments