[Tutor] slicing a string

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Tue Sep 7 10:19:37 CEST 2010


Op 2010-09-07 0:43, Alan Gauld schreef:
> 
> "lists" <lists at justuber.com> wrote
> 
>> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
>> doesn't work (as I expected it to) but that mytext[::-1] does.
>>
>> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't 
>> work?
> 
> It does work.
> But remember that slices give you the first item to one less
> than the second index, so for a 4 letter word you need an
> index of of -5...
> 
>>>> "test"[-1:-4:-1]
> 'tse'
>>>> "test"[-1:-5:-1]
> 'tset'
>>>>

But remember that you can make it simpler if you simply don't specify
the start and end points:

>>> 'hello'[::-1]
'olleh'

-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
  -- Isaac Asimov

Roel Schroeven



More information about the Tutor mailing list