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.
string.rstrip(characters)
The rstrip()
method takes in an optional parameter which is either a character
or string
to be removed from the end of the string.
The return value is of type string.
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 print
statement will remove all trailing whitespaces because no argument was passed.
The second print
statement takes in an argument, but the characters passed as an argument are not trailing characters, so nothing is removed from the string.
The third print
statement takes in trailing characters as an argument. These characters are removed from the string.