Python rstrip

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

String_Value.rstrip(Chars)
  • String_Value: A valid String literal.
  • Chars: This is an Optional parameter. If we Omit this, the rstrip function recognizes the white spaces as a default parameter. To modify, specify the Characters to strip from the string in Python.

Python rstrip Example

The following set of examples helps to understand the rstrip Function.

# Python RStrip Method Example

Str1 = 'Tutorial Gateway         '

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

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

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

First, we declared the String variable Str1 and assigned a string value

Str1 = 'Tutorial Gateway         ';

It removes the white spaces from the Right side of String variable Str1 using the rstrip function and prints the output

Str2 = Str1.rstrip()
print('Stripping White spaces on Right Side using RStrip() is =', Str2)

The rstrip function in python returns the output in a new string, instead of altering the original string.

print('Converted String is =', Str1.rstrip())
print('Original String is =', Str1)

To change the original String, write the following rstrip 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 Python statements, we have zeros on both sides. However, see that the rstrip function removed zeros from the Right-hand side only.

Str3 = '00000000Tutorial Gateway00000000'.rstrip('0')
print("Stripping 0's on Right Side using RStrip() is =", Str3)

In this Python String function example code, we used two characters to strip (+ and *) from the Right-hand side.

Str4 = 'Tutorial Gateway+++++*********'.rstrip('+*')
print('Stripping + and * on Right Side using RStrip() is =', Str4)