
Python's rstrip() Method
In the world of Python, the rstrip() method is a handy tool you can use to shave off trailing whitespace from a string.
string.rstrip()
You can call upon the rstrip() method with strings and objects of String type.
You can specify the character or group of characters you'd like to remove by placing them in parentheses. But if you leave it blank, the method will assume you're after the whitespace.
This method zeroes in on the trailing whitespace or any other specified characters at the end of the string.
Hence, the name rstrip, which is a shorthand for "right strip". What's particularly interesting is that the rstrip() method doesn't mess with the original string; instead, it whips up a new one.
To make things a bit more tangible, let's dive into some examples.
First, let's assign a string to a variable we'll call "text".
>>> text = " Hello World! ";
In the string "Hello World! ", notice the space lingering after the "!" character.
To swat it away, we can use the rstrip() method.
>>> text.rstrip()
What rstrip() does is scrub away all the trailing whitespace in the string, leaving any other spaces within or at the start of the string alone.
Hello world!
Bear in mind, though, that the original string tucked away in the "text" variable stays the same, as rstrip() gives you a new string.
The rstrip() method also gives you the power to specify the character or string of characters to pluck from the end of the string.
Let's say we create a variable called "bill", housing a string with asterisks at both ends.
>>> bill = "*****1.100***";
To clear out the trailing asterisks, you can call upon the rstrip("*") method.
>>> bill.rstrip("*")
This will only erase all "*" characters trailing at the end of the string, leaving everything else as it is.
*****1.100
And there you have it! You can use the rstrip() method to wipe out any other character or group of characters at the tail-end of a string.