Python String rstrip() Method



The Python String rstrip() method will remove all the specified characters in a string from the right (i.e. ending). That means, the method removes all combinations of the specified characters trailing the string until a different character is found. This method is a counterpart of the lstrip() method.

To elaborate, if the characters to be stripped are ‘af’ from a string “ababcdfffaf”, the result would be “ababcd”.

If the specified characters to be removed are not mentioned, the Python String rstrip() method will remove the trailing whitespaces if there are any.

Syntax

Following is the syntax for Python String rstrip() method −

str.rstrip([chars])

Parameters

  • chars − You can supply what chars have to be trimmed.

Return Value

This method returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters).

Example

If we initialize a string with unnecessary leading characters, the method will strip all the leading characters.

The following example shows the usage of Python String rstrip() method. Here, we are creating a string and passing a character to the rstrip() method as an argument.

str = "88888888this is string example....wow!!!8888888";
print(str.rstrip('8'))

When we run above program, it produces following result −

88888888this is string example....wow!!!

Example

If no parameters are passed to the rstrip() method, the output will be returned as the original string with trailing whitespaces removed.

In this example, we are creating a string input with leading and trailing whitespaces. Passing a whitespace argument or no parameters to the rstrip() method will remove the trailing whitespaces leaving the leading whitespaces as it is.

str = "     this is string example....wow!!!     ";
print(str.rstrip())
print(str.rstrip(' '))

When we run above program, it produces following result −

     this is string example....wow!!!
     this is string example....wow!!!

Example

If we pass a letter character for the input string, then only the trailing case-based characters are stripped.

In the following example, we create a string "this is string exampleeeEEEE" and call the rstrip() method on it. Since the method is case sensitive, only characters with same case are stripped.

str = "this is string exampleeeEEEE"
print(str.rstrip('E'))

When we run above program, it produces following result −

this is string exampleee
python_strings.htm
Advertisements