7

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?

Community
  • 1
  • 1

3 Answers3

14

.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"
kindall
  • 178,883
  • 35
  • 278
  • 309
  • i see... so how would one strip string1 exactly from the left of string2? if it helps, i know for sure that string2 is of the form string1+string3. –  Jan 30 '11 at 02:41
  • 4
    For a quick and dirty way `"my_string"[len("my"):]` – Falmarri Jan 30 '11 at 02:44
7

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'
Community
  • 1
  • 1
ephemient
  • 198,619
  • 38
  • 280
  • 391
2

To do what you want:

>>> a = "foobar"
>>> sub = "foo"
>>> b = a[len(sub):]
>>> b
'bar'
Harmen
  • 669
  • 3
  • 8