lstrip problem - beginner question

Larry Hudson orgnut at yahoo.com
Wed Jun 5 00:53:53 EDT 2013


On 06/04/2013 08:21 AM, 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?
>
> Thanks for your help and attention
> Max
>

The lstrip() function is the wrong one to use here.  The command help(str.lstrip) gives:

lstrip(...)
     S.lstrip([chars]) -> str

     Return a copy of the string S with leading whitespace removed.
     If chars is given and not None, remove characters in chars instead.

IOW, it does NOT strip the given string, but all the characters in the given string.
So in your second example it (correctly) removes everything and gives you an empty string as the 
result.

One possible alternative is to use slicing:

h02 = '>contig-100_0'
h03 = '>contig-100_'
result = h02[len(h03):]

Or some similar variation, possibly adding a startswith() function for some simple error 
checking.  Of course, other approaches are possible as well,

      -=- Larry -=-




More information about the Python-list mailing list