
Python rstrip and lstrip returns a copy of the string with right and left trailing characters removed, respectively.
s = " FirstName "
print(f"{s.rstrip()} LastName")
#Output
# FirstName LastName
By default rstrip will remove the trailing whitespaces to the right of the string, as seen above. We also use an f-string which you can found more about HERE.
There is an optional argument accepted by rstrip that allows us to specify an exact character to be excluded instead. In this case it will remove the specified character:
s = "-----FirstName------"
print(f"{s.rstrip('-')} LastName")
#output
#-----FirstName LastName
Note that rstrip only works on the right hand side, the specified character or whitespace will remain on the left side of the string.
Similarly, by default lstrip will remove the trailing whitespaces to the left of the string. Method lstrip also allows us to specify the optional argument:
s = " FirstName "
print(f"{s.lstrip()} LastName")
#output
#FirstName LastName
s = "______FirstName______"
print(f"{s.lstrip('_')} LastName")
#output
#FirstName______ LastName
Note that lstrip only works on the left hand side, the specified character or whitespace will remain on the right side of the string.
Finally we can use both lstrip and rstrip at the same time. This will strip or remove the whitespace or specified character as follows:
s = " FirstName "
print(f"{s.lstrip().rstrip()} LastName")
#output
#FirstName LastName
s = "______FirstName______"
print(f"{s.lstrip('_').rstrip('_')} LastName")
#output
#FirstName LastName
We can actually accomplish the same thing as above with strip. The strip method trims both the left and right side of the specified string. It works with both whitespaces and a specified character like lstrip and rstrip:
s = "______FirstName______"
print(f"{s.strip('_')} LastName")
#output
#FirstName LastName
s = " FirstName "
print(f"{s.strip()} LastName")
#output
#FirstName LastName
Finally, we can strip multiple characters if we wish:
s = "<<<<<<<< FirstName >>>>>>"
print(f"{s.strip('<> ')} LastName")
#output
#FirstName LastName
In the above example we stripped three characters from the right and left: <, > and ‘ ‘ (whitespace).
Find the full source code HERE. Thanks for reading! 👌👌👌
Check out our Python String Formatting tutorial HERE.