开发者

Why does str.lstrip strip an extra character? [duplicate]

This question already has answers here: How do I remove a substring from the end of a string? (24 answers) Closed 4 years ago.
>>> path = "/Volumes/Users"
>>> path.lstrip('/Volume')
's/Users'
>>> path.lstrip('/Vol开发者_开发问答umes')
'Users'
>>> 

I expected the output of path.lstrip('/Volumes') to be '/Users'


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


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


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


lstrip doc says:

Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping

So you are removing every character that is contained in the given string, including both 's' and '/' characters.


Here is a primitive version of lstrip (that I wrote) that might help clear things up for you:

def lstrip(s, chars):
    for i in range len(s):
        char = s[i]
        if not char in chars:
            return s[i:]
        else:
            return lstrip(s[i:], chars)

Thus, you can see that every occurrence of a character in chars is is removed until a character that is not in chars is encountered. Once that happens, the deletion stops and the rest of the string is simply returned

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜