Python rstrip Function | trim string from right

Python rstrip function is used to remove trailing characters (characters at the end a string). Whitespace is the default trailing character to remove if no character passed as parameter.

If you want remove (trim string):-



chars (optional) – specifying the set of characters to be removed.

Returns value

Returns a copy of the string with trailing characters stripped.

rstrip Function| trim string from right example

We will do multiple example using a this method.

1. Remove left side whitespace from strings example

Output:  EyeHunts

2. Remove special char

Output: EyeHunts

3. How to Remove substring from left

Will remove only first occurrence from right from given string.

Output: The Python code Easy

Runtime Error | rstrip()

You can use another data type to trim using a rstrip() function.

Output: AttributeError: type object ‘list’ has no attribute ‘rstrip’

Python rstrip Function trim string from right

Python rstrip n | NewLine

Removing “n” using Python rstrip newline will not work.

You have to use a replace(‘\n’, ”) function. See below example.

Q: What is difference between python rstrip vs strip?

Answer: rstrip() function is used to remove trailing characters and where the strip() function uses to remove leading and trailing char from the given string.

Q: How to rstrip remove newline python?

Answer: The strip() or rstrip()  methods removes whitespace by default, so there is no need to call it with parameters like ‘\t’ or ‘\n’.

However if you used it, still it will remove leading and trailing \n and \t.

Much better to use replace function to remove  \n and \t in the middle of the string.

Complete Example

Do comment if you have any doubts and suggestion on this topic- Python rstrip strings.

IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.