What is the string.rstrip method in Python?
The rstrip method will remove a set of trailing characters in a string and return a new string.
Syntax
string.rstrip([chars_to_remove])
The rstrip method will loop through all the characters of the string from the end of the string and check if the current character of the string is present in the passed chars_to_remove.
-
If the current character is present in
chars_to_remove, then that character will be removed. -
If the current character is not present, then the looping is stopped.
Parameters
chars: This is the set of characters to be removed from the
Return value
This method returns a new string in which the passed set of characters is removed.
Example 1
string = " space at the end is removed ";
string.rstrip();
In the code above, we have a string with whitespace at the start and end of the string. When we call the rstrip method without any arguments, the space at the end of the string is removed.
Example 2
string = "sun raises";
string.rstrip("s"); #sun raise
In the code above, we have a sun raises string and call the rstrip('s') method. The rstrip method will loop the string sun raises in reverse order:
-
Last first char:
sis present in the passed argument so it is removed from the string. Now, the string issun raise. -
Last second char:
eis not present in the passed argument, so looping is stopped and thesun raisestring is returned.
Example 3
string = "sun raises";
string.rstrip("seria ");
In the code above, we have a sun raises string and call the rstrip('seria ') method. The rstrip method will loop the string sun raises in reverse order:
-
Last first char:
sis present in the'seria 'so it is removed from the string. Now the result string issun raise. -
Last second char:
eis present in the'seria ', so it is removed from the string. Now the result string issun rais'. -
Last third char:
sis present in the'seria 'so it is removed from the string. Now the result string issun rai. -
Last fourth, fifth, sixth, and seventh characters are
i,a,r, andwhitespacerespectively. All these characters are present in'seria ', so these characters are removed. Now the string will besun. -
Last eighth char:
nis not present in the'seria ', so looping is removed. The result stringsunis returned.
Complete example
# Example 1string = " space at the end is removed "print(string.rstrip()); #space at the end is removed# Example 2string = "sun raises";print(string.rstrip("s")); #sun raise# Example 3string = "sun raises";print(string.rstrip("seria ")); #sun