Z.Q Z.Q - 16 days ago 7
Python Question

Python Index Conflict



This is a picture from an open course. Inside this pic,

s='Arthur'
,
s[5:2:-2] == 'ut'
. It makes sense, since
[:2]
is "Ar" and
[3:]
is "hur", but this is somehow wrong in reality. I typed
s[5:2:-2]
and the output was "rh". I also get it because index 5 is 'r', but since
:2
starts at 'r', reverse 5 should start at 'u'. It's really confusing and this is a really good course from the top university. Where is it going wrong?

Answer

Looks like the author did make a boo-boo. It's common advice to think of string indices as locations between letters, not the letters themselves, so index 5 is between u and r. But this mental aid is only appropriate for positive steps. It's easier to see with a negative step of 1: If you write s[5:4:-1], you will extract the letter to the right of index 5, i.e. r. Similarly, s[1:0:-1] will get you the second letter: r.

This means that s[5:4:-1] picks out s[5], i.e. it is the same string position as s[5:6:1], not s[4:5:1] as the creator of that image clearly assumed. In other words, the reality is that index 5 really picks out a character, not an inter-character position. Slices with negative step start at the character at index 5, and move backwards in steps. And slices really stop before the character at the second index of the slice; pretending that indexes are between characters is a nice intuitive aid, but as you've discovered it's only appropriate when the slice step is positive.