Python str.rstrip() function


str.rstrip() Function in Python

The str.rstrip() function in Python is used to remove trailing (right-side) whitespace or specified characters from the end of a string. Unlike str.strip(), which removes both leading and trailing characters, rstrip() only affects the right side of the string.

Syntax:

string.rstrip([chars])
  • string: The string from which you want to remove trailing characters.
  • chars (optional): A string specifying the set of characters to remove. If omitted, rstrip() will remove trailing whitespace (spaces, tabs, newlines) by default.

Example 1: Removing trailing whitespace

# Example 1: Removing trailing whitespace my_string = "Hello, Python! " stripped_string = my_string.rstrip() print(stripped_string) # Output: "Hello, Python!"

In this example:

  • The trailing spaces after "Hello, Python!" are removed.
  • The content of the string remains unchanged.

Example 2: Removing specific trailing characters

# Example 2: Removing specific trailing characters my_string = "Welcome###" stripped_string = my_string.rstrip("#") print(stripped_string) # Output: "Welcome"

Here:

  • The # characters at the end of the string are removed.
  • Characters at the beginning of the string are not affected.

Example 3: Removing multiple specified characters

# Example 3: Removing multiple specified trailing characters my_string = "Hello, Python!!!$$$" stripped_string = my_string.rstrip("!$") # Remove both '!' and '$' print(stripped_string) # Output: "Hello, Python"

In this case:

  • The function removes all occurrences of ! and $ from the right side of the string.
  • The content in the middle or left side remains unchanged.

Key Points:

  • str.rstrip() removes trailing (right-side) whitespace characters by default, such as spaces, tabs (\t), and newlines (\n).
  • You can specify which characters to remove by passing them as an argument.
  • Only the characters at the end (right side) of the string are removed.
  • It does not modify the original string but returns a new string with the modifications.

Example 4: Stripping trailing newline characters

# Example 4: Removing trailing newline characters my_string = "Hello, Python!\n\n" stripped_string = my_string.rstrip() print(stripped_string) # Output: "Hello, Python!"

Here:

  • The trailing newline characters (\n\n) are removed, but the rest of the string remains unchanged.