Python rstrip
Python String rstrip Method
The rstrip function in Python is utilized to eliminate any trailing characters from a string. This means it will remove all specified characters from the right end of the string. In the absence of a specified parameter, it defaults to removing all whitespace from the string. This method yields a string as its result.
Syntax of Python String rstrip Method
It has the following syntax:
rstrip([chars])
Parameters
- chars: the character that needs to be eliminated from the string.
Return
It returns string.
Different Examples for Python String rstrip Method
Let’s explore a few instances of the rstrip method in order to grasp its functionality more clearly.
Example 1
An uncomplicated illustration that does not accept any parameters. It eliminates all trailing whitespace characters from the string.
# Python rstrip() method example
# Variable declaration
str = "Python and C# "
# Calling function
str2 = str.rstrip()
# Displaying result
print("Old string: ",str)
print("New String: ",str2)
Output:
Old string: Python and C#
New String: Python and C#
Example 2
The string characters are eliminated according to the specified character type parameter. It produces a new string subsequent to the removal of the character.
# Python rstrip() method example
# Variable declaration
str = "Python and C#"
# Calling function
str2 = str.rstrip('#')
# Displaying result
print("Old string: ",str)
print("New String: ",str2)
Output:
Old string: Python and C#
New String: Python and C
Example 3
Determining the number of characters that have been eliminated is quite straightforward by measuring the length of the string. Consider the following illustration. The length of the string is shown alongside its actual value.
# Python rstrip() method example
# Variable declaration
str = "Python and C#"
# Calling function
str2 = str.rstrip('#')
# Displaying result
print("Old string: ",str, len(str))
print("New String: ",str2, len(str2))
Output:
Old string: Python and C# 11
New String: Python and C 10