[Tutor] IndexError: string index out of range

Liam Clarke cyresse at gmail.com
Wed Nov 3 01:35:59 CET 2004


And that would be the simpler, more elegant way I mentioned in my
disclaimer. : )


On Tue, 2 Nov 2004 14:28:46 -0800 (PST), Danny Yoo
<dyoo at hkn.eecs.berkeley.edu> wrote:
> 
> > These handmade indexing is allways hard to code. Better to use a for-loop:
> >
> > for char in fruit:
> >     print char
> >
> > for index,char in enumerate(fruit):
> >     print [index], char
> >
> > (but while this is fine coding style, it's not such a challenging
> > learning example ;-)
> 
> Hi Michael,
> 
> For this particular example, I'd actually recommend using a backwards
> slice.  Here's an example:
> 
> ###
> >>> message = 'this is a test of the emergency broadcast system'
> ###
> 
> We're already familiar with slicing whole sections of a list:
> 
> ###
> >>> message[3:7]
> 's is'
> ###
> 
> But it turns out that slicing is even more versatile: we can ask Python to
> give us every other letter, for example:
> 
> ###
> >>> message[::1]
> 'this is a test of the emergency broadcast system'
> >>>
> >>> message[::2]
> 'ti sats fteeegnybodatsse'
> >>>
> >>> message[::3]
> 'tss sot eeyrdsst'
> ###
> 
> The third component of the slice is the "step" between elements.  By
> default, we "step" consecutive elements, but we can easily use a larger
> step to jump through our sequence.
> 
> And it turns out that we can select a negative step:
> 
> ###
> >>> message[::-1]
> 'metsys tsacdaorb ycnegreme eht fo tset a si siht'
> >>>
> >>> message[3:7:-1]
> ''
> >>>
> >>> message[7:3:-1]
> ' si '
> ###
> 
> Hope this helps!
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.


More information about the Tutor mailing list