Why does str.lstrip strip an extra character?

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")

The argument passed to lstrip is taken as a set of characters!

>>> '   spacious   '.lstrip()
'spacious   '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'

See also the documentation

You might want to use str.replace()

str.replace(old, new[, count])
# e.g.
'/Volumes/Home'.replace('/Volumes', '' ,1)

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

For paths, you may want to use os.path.split(). It returns a list of the paths elements.

>>> os.path.split('/home/user')
('/home', '/user')

To your problem:

>>> path = "/vol/volume"
>>> path.lstrip('/vol')
'ume'

The example above shows, how lstrip() works. It removes '/vol' starting form left. Then, is starts again... So, in your example, it fully removed '/Volumes' and started removing '/'. It only removed the '/' as there was no 'V' following this slash.

HTH


Strip is character-based. If you are trying to do path manipulation you should have a look at os.path

>>> os.path.split("/Volumes/Users")
('/Volumes', 'Users')

Tags:

Python

String