Table of Contents Hide
The Python String rstrip() method is a built-in function that strips trailing characters based on the arguments passed to the function and returns the copy of a string.
The Syntax of
rstrip() method is:
rstrip() method takes one parameter, and it’s optional.
- chars(optional) – a set of characters representing string that needs to be removed from the right-hand side of the string.
If the chars argument is not passed, the
rstrip() function will strip whitespaces at the end of the string.
rstrip() method returns a copy of the string by stripping the trailing characters based on the arguments passed.
- If we do not pass any arguments to
rstrip()function, by default, all trailing whitespaces are truncated from a string.
- If the string does not have any whitespaces at the end, the string will be returned as-is, matching the original string.
- If the characters passed in the arguments do not match the characters at the end of the string, it will stop removing the trailing characters.
Example 1: Working with rstrip() method
# Only trailing whitespaces are removed text1 = ' Python Programming ' print(text1.rstrip()) # Remove the whitespace and specified character at # trailing end text2 = ' code its my code ' print(text2.rstrip(' code')) # Remove the specified character at # trailing end text3 = 'code its my code' print(text3.rstrip('code'))
Python Programming code its my code its my
Example 2 – How to use rstrip() method in the real world?
In the below example, we have a list of the price in dollars. However, the dollar sign is appended at both the trailing and leading end of each element. We can simply iterate the list and remove the dollar symbol at the right-hand side using the
rstrip() method as shown below.
price = ['$100$', '$200$', '$300$', '$400$', '$500$'] new_price =  for l in price: new_price.append(l.rstrip('$')) print(new_price)
['$100', '$200', '$300', '$400', '$500']