Python String rstrip() Method
rstrip() Removes the specified character at the end of string, default is white space, newline, carriage return and tab.
Python String rstrip() Syntax
rstrip() method syntax:
str.rstrip([chars])
Python String rstrip() Parameters
- chars – specify the characters to be deleted (default is whitespace)
Python String rstrip() Return Value
Returns the new string generated by removing the specified character from the end of the string.
Python String rstrip() Example#1
The following example shows the use of the rstrip() function to remove any of the matching characters from the right side of a String.
Here, in the arguments to the Python string rstrip() function, we pass a string with multiple characters. In this case, rstrip() will try to strip the supplied characters from the right side of the original String, as long as they match any of the characters in the given argument.
#!/usr/bin/python3
string = "api for demos, ok?"
print(string.rstrip('skei'))
Output:
Python String rstrip() Example#2
Use the rstrip() method to remove trailing whitespace from a string.
#!/usr/bin/python3
string = "apidemos.com "
print(string.rstrip())
Output:
Python String rstrip() Example#3
Python rstrip() returns the original string if it cannot strip the supplied characters.
#!/usr/bin/python3
# string which is to be stripped
string = "api for demos.com"
# string doesn't have trailing 'j' or 'z', thus the rstrip() method didn't update the string
print(string.rstrip('jz'))
Output: