[Tutor] IndexError: string index out of range

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Nov 2 23:28:46 CET 2004


> 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!



More information about the Tutor mailing list