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 Python rstrip string function is shown below.
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 string function Example
The Python 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)
The first statement removes the white spaces from the Right side of a variable Str1 using this Python rstrip 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 only removes the given characters from the Right side of a string and omits 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.