[Tutor] Splitting a string

Steven D'Aprano steve at pearwood.info
Wed Feb 9 11:30:42 CET 2011


tee chwee liong wrote:
> hi all,
>  
> the code works:
> ####
> s='00101'
> found = False
> for i,c in enumerate(s):
>     if c == '0':
>         print 'Lane fail',i
>         found = True
>     if not found: print 'All lanes PASS


No, it doesn't work. You haven't sufficiently tested it. It tells lies:


 >>> s='11100101'
 >>> found = False
 >>> for i,c in enumerate(s):
...     if c == '0':
...         print 'Lane fail',i
...         found = True
...     if not found: print 'All lanes PASS'
...
All lanes PASS
All lanes PASS
All lanes PASS
Lane fail 3
Lane fail 4
Lane fail 6

All lanes did NOT pass.



> the enumerate is checking from left to right. is it possible check from right to left? 
> for eg:s='00101'
> 
> Will give below result:
> Lane fail 1
> Lane fail 3
> Lane fail 4

for i,c in enumerate(reversed(s)) is the easiest way.



-- 
Steven



More information about the Tutor mailing list