Skip to main content

Python String rstrip() Function

The String rstrip() method removes any whitespace from the ending (trailing) of the string by default.

note

You can also specify the characters you want to strip by specifying the chars parameter of the rstrip() method.

Syntax

my_string.rstrip(chars)

rstrip() Parameters

Python String rstrip() function parameters:

ParameterConditionDescription
charsoptionalA string of characters to be removed from the string
note

If chars argument is not provided, all ending whitespaces are removed from the string.

rstrip() Return Value

Python String rstrip() function returns a copy of the string with ending characters stripped.

All combinations of characters in the chars parameter are removed from the end of the string until the first mismatch.

Examples

Example 1: Strip Whitespaces from Right with rstrip()

The rstrip() method allows to remove spaces from the right side of a string, returning a new string.

my_str = "   Hello   "
result = my_str.rstrip()
print(f"'{result}'") # Output: ' Hello'

output

'   Hello'

Note that newline \n, tab \t and carriage return \r are also considered whitespace characters!

my_str = "  Hello  \t\n\r "
result = my_str.rstrip()
print(f"'{result}'") # Output: ' Hello'

output

'  Hello'

Example 2: Strip Characters from Right with rstrip()

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

my_str = "aaabbbaaa"
result = my_str.rstrip('a')
print(result) # Output: aaabbb

output

aaabbb
note

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

For example:

my_str = 'xxxxAxxxxAxxxx'
result = my_str.rstrip('x')
print(result) # Output: xxxxAxxxxA

output

xxxxAxxxxA

Example 3: Strip Multiple Characters from Right with rstrip()

The chars parameter is not a prefix! All combinations of its values are stripped, until reaching a character of the string that is not contained in the set of characters in chars parameter.

For example, let's strip all the characters provided in the argument:

my_str = 'http://www.example.com/gigapath'
result = my_str.rstrip('aightp/')
print(result) # Output: http://www.example.com

output

http://www.example.com