Z.Q Z.Q - 1 year ago 108
Python Question

Python Index Conflict

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

s[5:2:-2] == 'ut'
. It makes sense, since
is "Ar" and
is "hur", but this is somehow wrong in reality. I typed
and the output was "rh". I also get it because index 5 is 'r', but since
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download