Python string.rstrip()

The rstrip() method returns a copy of the string by removing the trailing characters specified as argument. If the characters argument is not provided, all trailing whitespaces are removed from the string.

Trailing characters are those characters which occur at the end of the string (rightmost part of the string).




characters: (optional) A char or string to be removed from the end of the string.

Return Value:

A string.

The following examples demonstrates the rstrip() method.

Example: rstrip()
>>> mystr = '     Hello World     '
>>> mystr.rstrip() # removes trailing spaces
'     Hello World '
>>> mystr = '''
Python is 
a programming language
>>> mystr.rstrip()  # removes trailing \n
'\nPython is \na programming language'
>>> mystr = '----Hello World----'
>>> mystr.rstrip('-')  # removes trailing -
'----Hello World'

You can specify one or more characters as a string to be removed from the string in any order, as shown below.

Example: rstrip()
>>> '#$2Hello World#$2'.rstrip('$2#')
'#$2Hello World'
>>> 'Hello World#-$2'.rstrip('$2#')
'Hello World#-'
>>> ''.rstrip('/.') # remove www.
>>> 'bcā'.rstrip('ā') # removes Unicode char

In the above example, '#$2Hello World#$2'.rstrip('$2#') removes trailing chars'$', '2', or '#' even if appears in any order. However, Hello World#-$2'.rstrip('$2#') removes only trailing '$' and '2', because '-' is not specified to be removed, so it stops there and consider it as a word.

Want to check how much you know Python?