Python rstrip

The Python rstrip method is used to remove the specified characters from the Right hand side of a string. By default, it removes trailing whitespace characters and returns a new string. The syntax of the rstrip in Python Programming Language is

text.rstrip(Chars)
  • Chars: If we Omit this, it recognizes the white spaces as a default parameter. To modify, specify the Characters to strip from the string.

Python rstrip Example

The rstrip method returns a copy of the string with trailing characters removed from it. The following set of examples helps to understand this function.

Str1 = 'Tutorial Gateway         '

Str2 = Str1.rstrip()
print('Delete White sapces on Right Side using it is =', Str2)

# Observe the Original
print('Converted is =', Str1.rstrip())
print('Original is  =', Str1)
      
# Performing it directly
Str3 = '00000000Tutorial Gateway00000000'.rstrip('0')
print("Deleting 0's on Right Side using it is =", Str3)

# Remove Right Side
Str4 = 'Tutorial Gateway+++++*********'.rstrip('+*')
print('Deleting + and * on Right Side using it is =', Str4)
Python RStrip

The first statement removes the white spaces from the Right side of a variable Str1 using this function and prints the output.

The next print statement returns the output in a new string, instead of altering the original. To change the original, write the following statement

Str1 = Str1.rstrip()

The rstrip in Python only removes the given characters from the Right side of a string and omit Left-hand side characters.

Within the following Str3 Python statements, we have zeros on both sides. However, see that the method removed zeros from the Right-hand side only.

In this Str4 method example code, we used two characters to strip (+ and *) from the Right hand side.