String negative indices?

drtimhill at comcast.net drtimhill at comcast.net
Fri Jun 23 03:07:27 CEST 2006


I'm just starting out on Python, and am stumped by what appears an oddity in the way negative indices are handled.

For example, to get the last character in a string, I can enter "x[-1]". To get the 2nd and 3rd to last, I can enter x[-3:-1] etc. This is fine.

Logically, I should be able to enter x[-2:-0] to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I have to enter x[-2:].

With simple constants, this is ok, but it's a little more annoying when the start and end of the range are in variables somewhere. The only way I can find of making this work without lots of special-case "if" logic is to translate negative subscripts to positive, which kinda defeats the purpose of the negative subscripts anyway.

Is there some magic I'm missing here? Wouldn't it actually be better for Python to treat 0 as a special case here, so that x[-2:0] and x[-2:] generated the same result?

--Tim



More information about the Python-list mailing list