Python Strip

By | September 27, 2021
Python Strip

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

strip() syntax

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

strip() method can remove the characters from the left and right 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 as the user has mentioned them. The strip() method remove those spaces and print the text.

strip() method only deal with the initial and ending spaces and characters of a string. It does not remove the extra spaces between the characters.

Vamware

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 remove the space which was at the beginning and end of the string.

strip(char) parameter

We can pass a single character or string in the strip() method. And it will remove that character if it present at the beginning and 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

Summary

  • strip() method only remove the initial and trailing characters.
  • By default, the strip() method remove 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.

People are also reading: 

Author: Vinay

I am a Full Stack Developer with a Bachelor's Degree in Computer Science, who also loves to write technical articles that can help fellow developers.

Leave a Reply

Your email address will not be published. Required fields are marked *