The rstrip
method will remove a set of trailing characters in a string and return a new string.
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.
chars
: This is the set of characters to be removed from the
This method returns a new string in which the passed set of characters is removed.
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.
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: s
is present in the passed argument so it is removed from the string. Now, the string is sun raise
.
Last second char: e
is not present in the passed argument, so looping is stopped and the sun raise
string is returned.
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: s
is present in the 'seria '
so it is removed from the string. Now the result string is sun raise
.
Last second char: e
is present in the 'seria '
, so it is removed from the string. Now the result string is sun rais'
.
Last third char: s
is present in the 'seria '
so it is removed from the string. Now the result string is sun rai
.
Last fourth, fifth, sixth, and seventh characters are i
,a
, r
, and whitespace
respectively. All these characters are present in 'seria '
, so these characters are removed. Now the string will be sun
.
Last eighth char: n
is not present in the 'seria '
, so looping is removed. The result string sun
is returned.
# 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