Python rstrip Function | trim string from right

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

If you want to 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 examples using this method.

1. Remove left side whitespace from strings example

str1 = "  EyeHunts  "

Output:  EyeHunts

2. Remove special char

# Given string
string = "EyeHunts ***##"

# Removes given set of characters from Right.

Output: EyeHunts

3. How to Remove substring from left

Will remove only first occurrence from right from the given string.

string = "The Python code Easy Easy"


Output: The Python code Easy

Runtime Error | rstrip()

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

list1 = [1, 2, 3]


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.

string = "The \n Python \n code"

print(string.replace('\n ', ''))

Q: What is the 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 remove 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

str1 = "The \n Python \n code"

print(str1.replace('\n ', ''))

str2 = "The \t Python \t code"

print(str2.replace('\t ', ''))

Do comment if you have any doubts and suggestions 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.