Python String rstrip() Method

Python String Rstrip() Method

This is a tutorial of the Python String rstrip() method. Learn to get the copy of a given string with specified trailing characters removed from it.

Python String rstrip()

This method returns a new copy of the given string in which the characters specified in the argument are removed from the trailing edge of the string. (From Right-hand side)

Note. By default this method removes the trailing whitespaces, in case, no argument is supplied to this method. The characters to be removed has to be provided as a string containing the set of characters to be removed.

Syntax

Given below is the syntax for the Python String rstrip() method.

str.rstrip() Parameters

This method only takes a single argument and that is the chars. It is basically a string type argument that can contain a number of characters. These are the characters whose combinations you want to be removed from the trailing edge of the given string on which this method is applied.

In case, this argument is not passed to this method, all of the trailing whitespace characters will be removed by this method.

str.rstrip() Return Value

It returns the new copy of the string in which the specified trailing characters will be stripped off from the given string on which this method is applied.

If you provide more than one character as the string type argument of this method, then all of the possible combinations that are possible to be created using the string characters, if existing in the trailing edge of the given string will be removed or stripped until it founds the first mismatch.

Example: Basic usage of the Python String rstrip() method

Here in the following example, we’ve applied the method rstrip() on four different string to check what all characters are being removed in the returned copy of the string from the trailing edge with different arguments.

string1 = "hello, how are you?        "
#Using rstrip() without chars argument
#trailing whitespaces will be removed
print(string1.rstrip())

string2 = "yo hello world!"
#Char Argument Supplied
#No Space Character Mentioned
print(string2.rstrip('!dlrow'))
#Space Character Mentioned
print(string2.rstrip('!dlrow '))

string3 = "Java, Python, C, C++"
print(string3.rstrip('c, +'))
#Case Matters
print(string3.rstrip('C, +'))

string4 = "121213121212"
print(string4.rstrip("12"))

Output.

hello, how are you?
yo hello 
yo he
Java, Python, C, C
Java, Python
121213

I hope you found this guide useful. If so, do share it with others who are willing to learn Python and other programming languages. If you have any questions related to this article, feel free to ask us in the comments section.

And do not forget to subscribe to WTMatter!

Subscribe To WTMatter!

Receive updates of our latest articles via email. Enter your email address below to get started.

Leave a Reply

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