Python String rstrip() Method

Python provides a lot of methods in order to work with a string data type. rstrip() is one of them used to remove trailing characters. In this tutorial, we will examine different examples about rstrip() method. This method is provided for the string or str data type.

rstrip() Method Syntax

rstrip() method has very simple syntax where single parameter can be provided but it is optional.

STRING.rstrip(chars)
  • STRING is a string value or variable where the given chars will be removed.
  • chars parameter is optional. If not provided the default value will be space where the trailing spaces of the STRING will be removed. If char is provided given single or multiple characters will be removed from the start or the end of the given STRING if they exist.

Remove Trailing Spaces

One of the most popular use case for the rstrip() method is removing the trailing spaces which are at the start or at the end of the specified given string.

s1 ="  Wisetut"
s2 ="   Wisetut"
s3 ="   Wisetut  "
s4 ="Wisetut  "

s1.rstrip()
# '  Wisetut'

s2.rstrip()
# '   Wisetut'
 
s3.rstrip()
# '   Wisetut'

s4.rstrip()
# 'Wisetut'
Remove Trailing Spaces
Remove Trailing Spaces

Remove Specified Characters From Start and End Of The String

In the previous example, we ha not provided any parameter to the rstrip() method which is used to strip the right side or trailing spaces. We can also provide single or multiple characters to remove from the right side if they exist. You can see that repeated characters are stripped to even they are used one time as rstrip() parameter.

s1="Wisetut"
s2="Number99"

s1.rstrip('t')
# 'Wisetu'

s1.rstrip('ut')
#'Wiset'

s2.rstrip('9')

s2.rstrip('99')
Remove Specified Characters From Start and End Of The String

Leave a Comment