Python String rstrip()
Python String.rstrip() is used to strip/trim specified characters from the right side of this string. rstrip() method returns a new resulting string and does not modify the original string.
In this tutorial, we will learn the syntax and examples for rstrip() method of String class.
Syntax
The syntax to call rstrip() method on string x
in Python is
x.rstrip(characters)
where
Parameter | Required / Optional | Description |
---|---|---|
characters | Optional | A string. Any of these characters that are present on the right side of the string shall be trimmed. The default value is all whitespace characters. |
Examples
In the following program, we take a string '@hello world..@@@'
, and trim the characters '.@'
on the right side of the string.
Example.py
x = '@hello world..@@@'
result = x.rstrip('.@')
print('Original String : ', x)
print('Stripped String : ', result)
Output
Original String : @hello world..@@@
Stripped String : @hello world
If you observe, there is @
character on the left side of the string. Since, this character is not at right side, rstrip() does not trim this character.
Now, let us take a string with spaces on the left and right side, and trim this string using rstrip() method, with no arguments passed. Since the default value of characters
parameter is whitespaces, rstrip() trims the whitespace characters on the right side of this string.
Example.py
x = ' hello world\n\n'
result = x.rstrip()
print('Original String : ', x)
print('Stripped String : ', result)
Output
Original String : hello world
Stripped String : hello world
The new line characters on the right side of the string are trimmed.
Conclusion
In this Python Tutorial, we learned how to trim specified characters from the right side of the string using rstrip() method, with examples.