The Wayback Machine - https://web.archive.org/web/20241213200244/https://www.geeksforgeeks.org/python-string-rstrip/
Open In App

Python String rstrip() Method

Last Updated : 12 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The rstrip() method removes trailing whitespace characters from a string. We can also specify custom characters to remove from end of string.

Let’s take an example to remove whitespace from the ends of a string.

Python
s = "Hello Python!   "
res = s.rstrip()
print(res)

Output
Hello Python!

Syntax of rstrip() Method

s.rstrip(chars)

  • s: The input string
  • chars (optional): A set of characters to remove as trailing characters

Examples of rstrip() Method

Remove Trailing Whitespaces

Python
s = "   Hello Python!     "
res = s.rstrip()
print(res)

Output
   Hello Python!

Remove Custom Characters

If we have a string with various characters that we want to remove from end of the string.

Python
s = '  ##*#Hello Python!#**##  '

# removes all occurrences of '#', '*', and ' ' 
# from the end of string
res = s.rstrip('#* ')
print(res)

Output
  ##*#Hello Python!

Notes:

  • rstrip(‘#* ‘) removes any #, *, and spaces from the end of string.
  • It stops stripping characters from the end of string once it encounters a character that are not in the specified set of characters.

Remove Newline Characters

We can also remove the trailing newline characters (\n) from a string.

Python
s = '\nHello Python!\n'

# Removing newline characters
# from the end of string
res = s.rstrip()

print(res)

Output
Hello Python!

Frequently Asked Questions (FAQs) on Python rstrip() Method

What characters does rstrip() remove by default?

By default, rstrip() removes whitespace characters including spaces, tabs (\t), and newlines (\n), from the right end of the string.

Can rstrip() remove characters from the middle of a string?

No, rstrip() only removes characters from the end of a string. Characters in the middle of the string remain unaffected.

How is rstrip() different from strip() and lstrip()?

The rstrip() method removes characters only from the end of a string, while lstrip() removes characters from left only and strip() removes characters from both end.


Next Article

Similar Reads

Practice Tags :
three90RightbarBannerImg