[Tutor] Splitting a string

Peter Otten __peter__ at web.de
Tue Feb 8 15:15:36 CET 2011


Christian Witts wrote:

> On 08/02/2011 15:04, tee chwee liong wrote:
>> hi all,
>>
>> thanks for the advice. i modified my code to be:
>>
>> c=('01101')
>> i=-1
>> try:
>>     while 1:
>>         i=c.index('0',i+1)
>>         print "Lane fail",i
>> except ValueError:
>>     print "All Lanes PASS"
>>     pass
>>
>> when i run, the result is:
>>
>> >>>
>> Lane fail 0
>> Lane fail 3
>> All Lanes PASS
>>
>> Question: How do i prevent the code from executing the except
>> ValueError part. it seems to be checking bit by bit and when is see 1
>> it will execute the except part.
>> i just want the results to be:
>> >>>
>> Lane fail 0
>> Lane fail 3

> `while i < len(c)` instead of `while 1`

You have an off-by-one bug. But even if you fix that you'll still enter the 
except suite if the string c doesn't end with a "0". You need to keep track 
of the failed lanes, e. g.: 

for c in "011010", "111", "000", "", "1", "0", "001":
    print c.center(20, "-")

    i = -1
    all_passed = True
    try:
        while True:
            i = c.index('0', i+1)
            print "Lane fail", i
            all_passed = False
    except ValueError:    
        pass
    if all_passed:
        print "All Lanes PASS"




More information about the Tutor mailing list