[Tutor] conditionals with slicing not seeming to work

Alan Gauld alan.gauld at btinternet.com
Mon Jan 28 09:32:46 CET 2008

"Rob Stevenson" <rob.rstevenson at gmail.com> wrote

> I'm working at a certain website's puzzles using
> python in order to learn the language,

OK, Then I'll add some other comments

> the intention of this snippet is to only print slices where 
> character 1 is
> lower case, 2-4 and 6-8 are upper.  The logic here looks right to a 
> VB eye.

> etc...

> h = range(len(s)-9)
> for i in h:

more conventionally in python to just say

for i in range(len(s)-9)

>    j=s[i:i+8]
>    if j[0].islower():
>        if j[1:3].isupper():
>          if j[5:7].isupper():

And this would reflect the problem statement better if
you used boolean logic

if j[0].islower() and j[1:4].isupper() and j[5:8].isupper():
    print j

You could also do this using regular expressions if
you want an alternative approach.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list