
The Python strip() Method
Ever found yourself stuck with pesky white spaces or unwanted characters littering the start and end of your strings in Python? That's where the strip() method swoops in to save the day. Here's how it works:
string.strip(character)
This method can be applied to variables of the String type.
- The 'string' refers to the variable that holds the string you wish to apply the method to.
- The 'character' in parentheses is the one you wish to remove from the start and the end of the string.
The function returns a new string, devoid of the leading and trailing spaces (or the character you specified).
Note. The character within the parentheses is optional. If you leave it out, Python will default to the space character, i.e., the blank space.
For instance, let's create a string with some blank spaces at the beginning and the end.
>>> string = " Hello World "
Then, type string.strip() to apply the strip method to the string.
>>> string.strip()
The method returns the string, but without the leading and trailing blank spaces.
Hello World
The spaces in between the words are still there because the strip method does not remove those.
Note. Keep in mind that the strip() method returns a new string and does not alter the string stored in the variable. So, if you want to keep the result, you'll need to save it in a new variable.
>>> new_string = string.strip()
Or, you can overwrite the same variable.
>>> string = string.strip()
Let's go through another example.
Create a string with some "*" characters at the beginning and the end, and some in between.
>>> string="***Hello * World***"
Now, type string.strip('*') to remove the "*" character from the start and the end of the string.
>>> string.strip('*')
The operation yields the string "Hello * World".
Hello * World
The method has removed the "*" characters from the beginning and the end of the string, leaving the ones in between intact.