String rstrip() Method in Python

Python String rstrip() Method

In Python, the rstrip() method is used to remove trailing whitespace characters (spaces, tabs, and newline characters) from the right end of a string. It returns a new string with the trailing whitespace removed, leaving the original string unchanged.

The syntax of the rstrip() method is as follows:

string.rstrip(characters)

Parameters:

  • characters (optional): This parameter specifies the characters to be removed from the right end of the string. If not provided, it will remove all whitespace characters.

Return value:

  • The rstrip() method returns a new string with trailing whitespace characters removed.

Here are some examples to illustrate how the rstrip() method works:

Basic usage (removing whitespace from the right end)

text = "  Hello, World!   "
result = text.rstrip()
print(result)  # Output: "  Hello, World!"

Removing specific characters from the right end

text = ">>> Welcome to Python!!!>>>"
result = text.rstrip(">")
print(result)  # Output: ">>> Welcome to Python!!!"

Using rstrip() with a specific set of characters

text = "abracadabra"
result = text.rstrip("ar")
print(result)  # Output: "abracadab"

In these examples, the rstrip() method removes whitespace characters from the right end of the string in Example 1, and specific characters (">" in Example 2 and "ar" in Example 3) in addition to whitespace characters. The original string remains unchanged, and the method returns a new string with the desired modifications.