string.lstrip stripping too much?

Bengt Richter bokr at oz.net
Sun May 15 14:43:30 EDT 2005


On Sun, 15 May 2005 15:24:25 +0200, "joram gemma" <joram.gemma at pandora.be> wrote:

>Hello,
>
>on windows python 2.4.1 I have the following problem
>
>>>> s = 'D:\\music\\D\\Daniel Lanois\\For the beauty of Wynona'
>>>> print s
>D:\music\D\Daniel Lanois\For the beauty of Wynona
>>>> t = 'D:\\music\\D\\'
>>>> print t
>D:\music\D\
>>>> s.lstrip(t)
>'aniel Lanois\\For the beauty of Wynona'
>>>> 
>
>why does lstrip strip the D of Daniel Lanois also?
>
Because the lstrip argument is a set of characters in the form of
a string, not a single substring to replace from the left. Note:
(repeating your example to start with)

 >>> s = 'D:\\music\\D\\Daniel Lanois\\For the beauty of Wynona'
 >>> print s
 D:\music\D\Daniel Lanois\For the beauty of Wynona
 >>> t = 'D:\\music\\D\\'
 >>> print t
 D:\music\D\
 >>> s.lstrip(t)
 'aniel Lanois\\For the beauty of Wynona'

Now we make an equivalent lstrip argument from your t argument
 >>> t2 = ''.join(sorted(set(t)))
 >>> print t2
 :D\cimsu

Note that there is only one of each character in t2 (e.g. 'D' and '\\')
And the result is the same for t and t2:

 >>> s.lstrip(t)
 'aniel Lanois\\For the beauty of Wynona'
 >>> s.lstrip(t2)
 'aniel Lanois\\For the beauty of Wynona'

If you want to replace an exact prefix, a regex could be a simple way
to get the startswith check and replace in one whack.

Regards,
Bengt Richter



More information about the Python-list mailing list