10

I ran into what I think is a bug, and I'm looking for confirmation or that I am not understanding how this method works.

Here's my basic output:

(Pdb) x = 'KEY_K'
(Pdb) x.lstrip('K')
'EY_K'
(Pdb) x.lstrip('KE')
'Y_K'
(Pdb) x.lstrip('KEY')
'_K'
(Pdb) x.lstrip('KEY_')
''
(Pdb) import sys
(Pdb) sys.version
'2.7.11 (default, Dec  5 2015, 14:44:47) \n[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.1.76)]'

My understanding is that the final 'lstrip' in that example should have returned 'K', but it did not. Does anyone know why?

Brian Bruggeman
  • 5,008
  • 2
  • 36
  • 55

3 Answers3

12

The lstrip() function doesn't behave in exactly the way you think it might. x.lstrip(argument) removes any of the characters in argument from the left of the string x until it reaches a character not in argument.

So 'KEY_K'.lstrip('KEY_') generates '' because the last character, K, is in KEY_.

gtlambert
  • 11,711
  • 2
  • 30
  • 48
8

It's right in the docs:

lstrip(...) S.lstrip([chars]) -> string or unicode

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

'K' is in 'KEY_', that's why your last example returns ''.

Note that 'K' would not have been removed if preceded by a character that is not in 'KEY_':

>>> 'KEY_xK'.lstrip('KEY_')
'xK'
timgeb
  • 76,762
  • 20
  • 123
  • 145
7

The second arg of lstrip is the set of characters that will be removed. If you need to remove a substring, you may use:

if x.startswith('KEY_'):
    x = x.replace('KEY_', '', 1)
Eugene Primako
  • 2,767
  • 9
  • 26
  • 35