What is rstrip() in Python?

The rstrip() method is an built-in method in Python used to remove all the specified characters from the right side of a string.

If no argument is passed, then it removes all trailing whitespaces from the string. The trailing characters are those characters that occur at the end of the string.

Syntax

string.rstrip(characters)

Parameters

The rstrip() method takes in an optional parameter which is either a character or string to be removed from the end of the string.

Return value

The return value is of type string.

Code

The sample code below demonstrates how to work with the rstrip() method.

sample_string = "My name is Charles "
print(sample_string.rstrip())
print(sample_string.rstrip("an em"))
print(sample_string.rstrip(" les"))
  • In the code above, the first print statement will remove all trailing whitespaces because no argument was passed.

  • The second print statement takes in an argument, but the characters passed as an argument are not trailing characters, so nothing is removed from the string.

  • The third print statement takes in trailing characters as an argument. These characters are removed from the string.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources