[Tutor] IndexError: string index out of range

Eri Mendz jerimed at myrealbox.com
Wed Nov 3 06:17:56 CET 2004


Dear All,

Thanks a lot for the good advise and tips given to me. Will get back 
here if i have question on the subject issue.

-- 
Regards,
erimendz ** use firefox/thunderbird **
http://www.spreadfirefox.com/?q=affiliates&id=6670&t=58


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



More information about the Tutor mailing list