Understanding python lstrip method for strings

I came across what, in my opinion, is a mistake, and I am looking for confirmation or that I do not understand how this method works.

Here is my main conclusion:

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

I understand that the final "lstrip" in this example should have returned "K", but that is not the case. Does anyone know why?

+6
source share
3 answers

This is correct in the docs:

lstrip (...) S.lstrip ([chars]) → string or unicode

Return a copy of line S with leading spaces removed. If characters are specified rather than None, delete characters in characters instead . If the characters are Unicode, S will be converted to Unicode before deletion

'K' is in 'KEY_' , so your last example returns '' .

Note that 'K' not deleted if it was preceded by a character that is not in 'KEY_' :

 >>> 'KEY_xK'.lstrip('KEY_') 'xK' 
+4
source

The lstrip() function does not work as you think. x.lstrip(argument) removes any character in argument left of line x until it reaches a character other than argument .

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

+5
source

The second argument to lstrip is the set of characters to be deleted. If you need to remove a substring, you can use:

 if x.startswith('KEY_'): x = x.replace('KEY_', '', 1) 
+1
source

All Articles