Python str.rstrip() function
str.rstrip()
Function in Python
The str.rstrip()
function in Python is used to remove trailing (right-side) whitespace or specified characters from the end of a string. Unlike str.strip()
, which removes both leading and trailing characters, rstrip()
only affects the right side of the string.
Syntax:
string
: The string from which you want to remove trailing characters.chars
(optional): A string specifying the set of characters to remove. If omitted,rstrip()
will remove trailing whitespace (spaces, tabs, newlines) by default.
Example 1: Removing trailing whitespace
In this example:
- The trailing spaces after
"Hello, Python!"
are removed. - The content of the string remains unchanged.
Example 2: Removing specific trailing characters
Here:
- The
#
characters at the end of the string are removed. - Characters at the beginning of the string are not affected.
Example 3: Removing multiple specified characters
In this case:
- The function removes all occurrences of
!
and$
from the right side of the string. - The content in the middle or left side remains unchanged.
Key Points:
str.rstrip()
removes trailing (right-side) whitespace characters by default, such as spaces, tabs (\t
), and newlines (\n
).- You can specify which characters to remove by passing them as an argument.
- Only the characters at the end (right side) of the string are removed.
- It does not modify the original string but returns a new string with the modifications.
Example 4: Stripping trailing newline characters
Here:
- The trailing newline characters (
\n\n
) are removed, but the rest of the string remains unchanged.