7
votes

Possible Duplicate:
Is this a bug in Python 2.7?

The .lstrip() function doesn't quite work as I expected on some strings (especially ones with underscores). e.g.,

In [1]:  a='abcd_efg_hijk_lmno_pqrs_tuvw_xyz'   
In [2]: a.lstrip('abcd_efg')   
Out[2]: 'hijk_lmno_pqrs_tuvw_xyz'

Here, the '_' between 'g' and 'h' is missing. Any idea as to why this happens?

3

3 Answers

14
votes

.lstrip() doesn't do what you think it does. It removes any of the provided characters from the left end of the string. The second underscore is as much an underscore as the first, so it got removed too.

"aaaaaaaabbbbbbbc".lstrip("ab")  # "c"
7
votes

What you want:

b = 'abcd_efg'
if a.startswith(b):
    a = a[len(b):]

As the str.lstrip documentation says,

The chars argument is not a prefix; rather, all combinations of its values are stripped:

>>> 'www.example.com'.lstrip('cmowz.')
'example.com'
2
votes

To do what you want:

>>> a = "foobar"
>>> sub = "foo"
>>> b = a[len(sub):]
>>> b
'bar'