Python String rstrip() Method

Strips characters from the right end of a string

Usage

The strip() method removes whitespace from the right end (trailing) of the string by default.

By adding chars parameter, you can also specify the characters you want to strip.

Syntax

string.rstrip(chars)

Python string rstrip() method parameters
ParameterConditionDescription
charsoptionalA list of characters to be removed from the string

Return Value

The method return a copy of the string with the specified characters removed from the right end of a string.

Strip Whitespace

By default, the method removes trailing whitespace.

Example: Strip whitespace from the right end

S = '   Hello, World!   '
x = S.rstrip()
print(x)

Input:

   Hello, World!   

Stripped:

   Hello, World!   

Output:

   Hello, World!

Newline '\n', tab '\t' and carriage return '\r' are also considered as whitespace characters.

Example: Strip newline ‘\n’, tab ‘\t’ and carriage return ‘\r’

S = '    Hello, World! \t\n\r '
x = S.rstrip()
print(x)

Input:

    Hello, World! \t\n\r 

Stripped:

    Hello, World! \t\n\r 

Output:

    Hello, World!

Strip Characters

By adding chars parameter, you can also specify the character you want to strip.

Example: Strip single character ‘a’

S = 'baaaaa'
x = S.rstrip('a')
print(x)

Input:

baaaaa

Stripped:

baaaaa

Output:

b

Strip Multiple Characters

The chars parameter is not a suffix; rather, all combinations of its values are stripped.

In below example, strip() would strip all the characters provided in the argument i.e. ‘w’, ‘o’ and ‘/’

Example: Strip multiple characters

S = 'example.com/wow'
x = S.rstrip('wo/')
print(x)

Input:

example.com/wow

Stripped:

example.com/wow

Output:

example.com

More About rstrip() Method

Characters are removed from the trailing end until reaching a string character that is not contained in the set of characters in chars.

Example:

S = 'xxxxSxxxxSxxxx'
x = S.rstrip('x')
print(x)

Input:

xxxxSxxxxSxxxx

Stripped:

xxxxSxxxxSxxxx

Output:

xxxxSxxxxS
Python rstrip Method Example Explanation

Here is another example:

Example:

S = 'Version 3.2 Model-32 - ...'
x = S.rstrip('.- ')
print(x)

Input:

Version 3.2 Model-32 - ...

Stripped:

Version 3.2 Model-32 - ...

Output:

Version 3.2 Model-32