Python String rstrip() Method With Example

Python String rstrip

Now, we are going to learn about the rstrip method. Using the rstrip method, we get a copy of the string, with the trailing characters removed. We can give a string argument to the rstrip method, specifying the set of characters to be removed. If we do not specify the string argument, then it defaults to remove the trailing whitespaces. Let’s have a look at a simple program, which demonstrates the same thing.

Python String rstrip() Method

As you can see in the program, we have a string, with the leading and trailing whitespaces. Then we are trying to call the rstrip method, which returns a string, with the trailing whitespaces/characters removed. In the above case, the trailing whitespaces would be removed. You can try executing the program and observing the output as well.

By providing a string argument to the rstrip method, we can specify the set of characters to be 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 the string, with some leading and trailing hyphen signs. After that, we are trying to call the rstrip method. We have specified the string argument as a hyphen, which we want to be removed. If you try to execute the above program and observe the output, you can see that a string with the trailing characters was returned from the rstrip method. Let’s have a look at the output now –

—–GyaniPandit

As you can see that we have the trailing characters removed from the string. Remember that the copy of the string is returned with the trailing characters removed.

So, as and when required. We can make use of the rstrip method, which returns a copy of the string, with all the trailing characters/whitespaces removed from the string. We can specify a string as an argument, which specifies the set of characters to be removed.