In Python, the string data type supports a
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.
# 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.
string = " TechGeekBuzz " # without strip() method print(string) # with strip() method print(string.strip())
Behind the Code
In the above example, the
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
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.
string = " Tech Geek Buzz " # without strip() method print(string) # with strip() method print(string.strip())
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
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.
string = "heading Tech Geek Buzz heading" # it will remove the heading from the end and beginning print(string.strip("heading"))
Tech Geek Buzz
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: