[Tutor] slicing a string

Sandip Bhattacharya sandipb at foss-community.com
Thu Sep 9 07:49:39 CEST 2010

On Tue, Sep 7, 2010 at 1:49 PM, Roel Schroeven
<rschroev_nospam_ml at fastmail.fm> wrote:
> 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?
  - Especially, when S[0:len(S):1] works that way?

- Sandip

More information about the Tutor mailing list