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)
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.rstrip()
method returns a new string with trailing whitespace characters removed.Here are some examples to illustrate how the rstrip()
method works:
text = " Hello, World! "
result = text.rstrip()
print(result) # Output: " Hello, World!"
text = ">>> Welcome to Python!!!>>>"
result = text.rstrip(">")
print(result) # Output: ">>> Welcome to Python!!!"
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.