Python String rstrip() Method – Remove Trailing Characters

Python String rstrip() Method

The rstrip() method in Python is used to remove trailing characters (characters at the end) from a string. By default, it removes any whitespace characters (like space, tab, or newline) from the right side of the string.

Syntax

string.rstrip([chars])

Parameters:

  • chars (optional) – A string specifying the set of characters to be removed. If omitted, whitespace is removed.

Returns:

  • A copy of the string with trailing characters removed.

Example 1: Remove Trailing Whitespace

text = "Hello World   "
result = text.rstrip()
print(result)
Hello World

Example 2: Remove Specific Trailing Characters

text = "hello!!!"
result = text.rstrip("!")
print(result)
hello

Use Case: Cleaning Up User Input

You can use rstrip() to clean up strings where extra characters are present at the end — for example, when reading data from a file:

line = "data123***\n"
cleaned = line.rstrip("*\n")
print(cleaned)
data123

Difference Between rstrip(), lstrip(), and strip()

  • rstrip() – removes from the right end
  • lstrip() – removes from the left end
  • strip() – removes from both ends

Common Mistake

  • Note: rstrip() removes characters as a set, not a sequence. For example, rstrip("!d") removes any combination of ! or d until it finds a character not in the set.

Interview Tip

Use rstrip() when working with file lines or logs where trailing newlines or specific characters need to be stripped safely.

Summary

  • rstrip() removes characters from the right side.
  • By default, it removes whitespace.
  • You can specify a custom set of characters to remove.
  • Returns a new string, doesn't change the original.

Practice Problem

Write a program to remove all trailing dollar signs '$' from a user-input string.

user_input = input("Enter a string with trailing $: ")
print("Cleaned:", user_input.rstrip("$"))