W3Basic Logo

Python String rstrip() Method

The str.rstrip() method removes the trailing characters (characters at the end of the string) specified in the chars argument and returns the copy of the string. If the chars argument is not passed, the rstrip() method removes trailing whitespaces in the string.

Example:

# Remove trailing characters from a string
text = "#####Hello, World!#####"
print(text.rstrip("#"))  # Output: "#####Hello, World!"

Output

#####Hello, World!

What are Trailing and Leading Characters?

Trailing Characters: The characters that appear at the end of the string are called the trailing characters.

Leading Characters: The characters appearing at the beginning of the string are called leading characters.


Syntax

The Syntax of the str.rstrip() function is:

str.rstrip(chars)

Here, str is a string.

Parameters

The str.rstrip() function can take one parameter.

  • chars (optional) - A character or string that needs to be removed at the trailing end of the string(right-hand side of the string).

Return Value

The str.rstrip() function returns a copy of a string by stripping the trailing characters based on the argument.

  • if the char argument is passed and found in the string at the trailing end, it will be removed.
  • If the char argument is not passed, all the whitespaces are stripped at the right side(trailing) of the string.

Example: How to use the rstrip() method in Python

In the first example, we remove the trailing whitespaces from the string " Hello, World! " using the rstrip() method.

In the second example, we remove the trailing dashes from the string "---Hello, World!---" using the rstrip() method with the argument "-".

In the third example, we remove the trailing characters 'x', 'y', and 'z' from the string "xyzHello, World!xyz" using the rstrip() method with the argument "xyz".

In the fourth example, we remove the trailing spaces and tab characters from the string " \tHello, World! " using the rstrip() method.

# Remove trailing whitespaces from a text
text = "   Hello, World!   "
print(text.rstrip())  # Output: "Hello, World!   "

# Remove trailing dashes from a text
text = "---Hello, World!---"
print(text.rstrip("-"))  # Output: "Hello, World!---"

# Remove trailing characters specified in a text
text = "xyzHello, World!xyz"
print(text.rstrip("xyz"))  # Output: "Hello, World!xyz"

# Remove trailing spaces and tab characters from a string
text = "   \tHello, World!   \t"
print(text.rstrip())  # Output: "Hello, World!   "

Output

   Hello, World!
---Hello, World!
xyzHello, World!
      Hello, World!  

Reference: Python Official Docs

© 2023 W3Basic. All rights reserved.

Follow Us: