Python String strip() Method With Example

Python String strip

Now, we are going to learn about the strip method. With the strip method, we get a copy of the string, with the leading and trailing characters removed. We can specify a string as an argument to the strip method, which specifies the set of characters to be removed. If we do not specify anything, it defaults to removing the leading and the trailing characters from the string. Let’s have a look at a simple program, which tries to demonstrate the same thing.

Python String strip() Method

As you can see in the above program, we have a string, with some leading and trailing hyphens. Then we are calling the strip method, and the string argument specifying the characters that need to be removed from the string is also given. So, the return value that we get from the strip method is the copy of the string, with the leading and trailing characters removed from the string. So, if you execute the program and have a look at the output, you can find that the leading and trailing characters are removed from the returned string. Let’s have a look at our output too.

GyaniPandit

As you can see, the leading and the trailing characters were removed. Also, we can provide multiple characters to be removed. Have a look at the below program, which demonstrates the same thing.

As you can see in the program, we have a string, and then we are trying to call the strip method, we have specified the string with multiple characters. So in the above case, the trailing hyphens and the exclamation marks are removed as well. You can try executing the program and observing the output, and you would find that the leading and trailing specified characters were removed from the string.

Let’s say that we do not pass any string argument to the strip method. In such a case, the strip method would return a copy of the string, with the leading and trailing whitespaces removed from the string. Let’s have a look at a simple program, which demonstrates the same thing.

As you can see in the above program, we have a string, with the leading and trailing whitespaces. After that, we are calling the strip method, to which, we have not passed any string argument, specifying the set of characters to remove. In this case, the strip method is going to return a string, with the leading and trailing whitespaces removed from the string. The original string is as it was.

You can try executing the program and observing the output. You would simply find that the leading and trailing whitespaces are removed.

So, as and when required, we can make use of the strip method in our python program. Remember that using the strip method, we get a string, with the leading and the trailing whitespaces/characters removed.