>>> path = "/Volumes/Users" >>> path.lstrip('/Volume') 's/Users' >>> path.lstrip('/Volumes') 'Users' >>>
I expected the output of path.lstrip('/Volumes')
to be '/Users'
To remove only leading whitespace and characters, use . lstrip() . This is helpful when you want to remove whitespace and characters only from the start of the string. An example for this would be removing the www.
rstrip(): returns a new string with trailing whitespace removed. It's easier to remember as removing white spaces from “right” side of the string. lstrip(): returns a new string with leading whitespace removed, or removing whitespaces from the “left” side of the string.
Introduction to Python string strip() method If you omit the chars argument or use None , the chars argument will default to whitespace characters. In other words, the strip() will remove leading and trailing whitespace characters from the str .
The lstrip() method returns a copy of the string with leading characters removed (based on the string argument passed). The lstrip() removes characters from the left based on the argument (a string specifying the set of characters to be removed).
lstrip
is character-based, it removes all characters from the left end that are in that string.
To verify this, try this:
"/Volumes/Users".lstrip("semuloV/") # also returns "Users"
Since /
is part of the string, it is removed.
You need to use slicing instead:
if s.startswith("/Volumes"): s = s[8:]
Or, on Python 3.9+ you can use removeprefix
:
s = s.removeprefix("/Volumes")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With