lstrip problem - beginner question

Peter Otten __peter__ at web.de
Tue Jun 4 11:52:37 EDT 2013


mstagliamonte wrote:

> Hi everyone,
> 
> I am a beginner in python and trying to find my way through... :)
> 
> I am writing a script to get numbers from the headers of a text file.
> 
> If the header is something like:
> h01 = ('>scaffold_1')
> I just use:
> h01.lstrip('>scaffold_')
> and this returns me '1'
> 
> But, if the header is:
> h02: ('>contig-100_0')
> if I use:
> h02.lstrip('>contig-100_')
> this returns me with: ''
> ...basically nothing. What surprises me is that if I do in this other way:
> h02b = h02.lstrip('>contig-100')
> I get h02b = ('_1')
> and subsequently:
> h02b.lstrip('_')
> returns me with: '1' which is what I wanted!
> 
> Why is this happening? What am I missing?

"abba".lstrip("ab")

does not remove the prefix "ab" from the string "abba". Instead it removes 
chars from the beginning until it encounters one that is not in "ab". So

t = s.lstrip(chars_to_be_removed)

is roughly equivalent to

t = s
while len(t) > 0 and t[0] in chars_to_be_removed:
    t = t[1:]

If you want to remove a prefix use

s = "abba"
prefix = "ab"
if s.startswith(prefix):
    s = s[len(prefix):]






More information about the Python-list mailing list