Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding python's lstrip method on strings [duplicate]

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?

like image 449
Brian Bruggeman Avatar asked Dec 31 '15 09:12

Brian Bruggeman


2 Answers

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)
like image 68
Eugene Primako Avatar answered Sep 29 '22 13:09

Eugene Primako


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_.

like image 36
gtlambert Avatar answered Sep 29 '22 13:09

gtlambert