Python String rstrip() Method
The rstrip()
method removes trailing characters (characters at the end) from a string. By default, it removes whitespace characters such as tabs, spaces, and newlines.
Syntax
string.rstrip([chars])
Parameter
chars
(Optional): A string specifying the set of characters to be removed. If this argument is omitted or None
, all trailing whitespace characters are removed.
Return Value
Returns a new string with specified trailing characters removed. It doesn’t modify the original string.
Examples
Basic Usage (Removing Whitespaces)
text = " Python is awesome "
stripped_text = text.rstrip()
print(stripped_text) # Output: " Python is awesome"
Removing Specific Characters
text = "xxxPython is awesome!xxx"
stripped_text = text.rstrip("x")
print(stripped_text) # Output: "xxxPython is awesome!"
The rstrip()
method only removes characters from the end (right side) of the string.
Removing Multiple Characters
text = "abcPython is awesome!bca"
stripped_text = text.rstrip("abc")
print(stripped_text) # Output: "abcPython is awesome!"
In this example, the rstrip()
method is not removing the exact substring "abc"
. Instead, it removes any combination of the characters "a"
, "b"
, or "c"
from the end of the string.
If you need to remove characters only from the beginning of the string, use the lstrip()
method.
If you need to remove characters both from the beginning and the end of the string, use the strip()
method.