String rstrip() Method Example | How to Use String rstrip() Function in Python

Python String rstrip() is an inbuilt method that returns a copy of the String with trailing characters removed. The rstrip() function returns the copy of the String in which all characters have been stripped from the end of the string and default whitespace characters.

One most important point to note here that these functions do not make inplace changes, and thus, these changes are just temporary.

If you want to make these modifications permanent then, you need to assign it to another variable to store the changed String because it returns the changed String.

Another important thing is by default, and it removes whitespaces if you don’t mention the character.

Syntax

string.rstrip([chars])

rstrip() Parameters

  • chars (optional) - a string specifying the set of trailing characters to be removed.
  • The rstrip() removes characters from the right based on the argument (a string specifying the set of characters to be removed).
  • If chars argument is not provided, all whitespaces on the right are removed from the string.

Return Value from rstrip()

  • The rstrip() returns a copy of the string with trailing characters stripped.
  • All combinations of characters in chars argument are removed from the right of the string until the first mismatch.

Example 1: How to Use the String rstrip() Method

rand_str = "Harry Potter   "
result = rand_str.rstrip()
print(result);

Output

Harry Potter

Example 2: Removing trailing characters

Visual Representation of Removing trailing characters
rand_str = "Harry Potter"
result = rand_str.rstrip("tter")
print(result);

Output

Harry Po

Example 3: What if the string cannot be stripped of provided characters

string = "homer simpson"

print(string.rstrip('sim'))

Output

homer simpson

Thanks for reading !!!

#python

String rstrip() Method Example | How to Use String rstrip() Function in Python
1.55 GEEK