What is rstrip() in Python?
The rstrip() method is an built-in method in Python used to remove all the specified characters from the right side of a string.
If no argument is passed, then it removes all trailing whitespaces from the string. The trailing characters are those characters that occur at the end of the string.
Syntax
string.rstrip(characters)
Parameters
The rstrip() method takes in an optional parameter which is either a character or string to be removed from the end of the string.
Return value
The return value is of type string.
Code
The sample code below demonstrates how to work with the rstrip() method.
sample_string = "My name is Charles "print(sample_string.rstrip())print(sample_string.rstrip("an em"))print(sample_string.rstrip(" les"))
-
In the code above, the first
printstatement will remove all trailing whitespaces because no argument was passed. -
The second
printstatement takes in an argument, but the characters passed as an argument are not trailing characters, so nothing is removed from the string. -
The third
printstatement takes in trailing characters as an argument. These characters are removed from the string.