[Tutor] slicing a string

Evert Rol evert.rol at gmail.com
Thu Sep 9 08:04:04 CEST 2010

>> But remember that you can make it simpler if you simply don't specify
>> the start and end points:
>>>>> 'hello'[::-1]
>> 'olleh'
> While I know that idiom works, I haven't really found an explanation
> as to *why* it works that way.
> For a string S:
> * Using  range, you need range(len(S),-1,-1) to give you the indexes
> for the string in reverse.
> * For slices, if you dont specify the start and end indices, they are
> supposed to be filled in by 0 and len(S) respectively.
>  - So S[::-1] means, S[0:len(S):-1] , so why dont we start with index
> 0 here, and then go to -1 (last char) and then into an infinite loop?

I guess because Python "is smart", and works the way you want/expect it to.
Read http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange , note 5 (about one "page" down), which explicitly says "If i or j are omitted or None, they become “end” values (which end depends on the sign of k)", where the important bit for this discussion is actually between parentheses.

And to quote part of the Zen of Python:
Special cases aren't special enough to break the rules.
Although practicality beats purity.

Reversing the automatic end values is very practical when the step index < 0.

>  - Especially, when S[0:len(S):1] works that way?
> - Sandip
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list