[Pythonmac-SIG] string index bug?

Dan Wolfe dkwolfe at pacbell.net
Fri Jan 30 23:35:50 EST 2004


In python, indexes are defined by [index] or [startIndex:endIndex], and 
NOT [startIndex:count] and are zero based.
The use of negative indexes means count from the end.  If the parameter 
is missing (like [:2] [2:]), it means start from the beginning or  
continue to the end depending on the location.  If both are missing 
it's gives you a copy..

Thus given the the string "food"

 >>> "food"[:-1]
'foo'
 >>> "food"[-3:]
'ood'
 >>> "food"[-3:-1]
'oo'
 >>> "food"[0]
'f'
 >>> "food"[0:-3]
'f'
 >>> "food"[-3:0]
''
In the last case, the start index is AFTER to the end index, so 
logically it returns a empty string.
And missing values are...

 >>> a = "food"
 >>> b= a[:]
 >>> b
'food'

The same logic also applies to lists and tuples... here's an example 
using a list..

 >>> a = [0,1,2,3]
 >>> a[0]
0
 >>> a[3]
3
 >>> a[-1]
3
 >>> a[-3]
1
 >>> a[1:3]
[1, 2]
 >>> a[-2:-1]
[2]
 >>> a[-3:-1]
[1, 2]

Hope this helps...

- dan


On Jan 30, 2004, at 6:25 PM, Keith Nemitz wrote:

This one's so unbelievable, I'd rather be ridiculed for not 
understanding TFM than let a potential bug slip. I'm running macPython 
2.3 on Panther.

Drop into python from Terminal. Type

 >>>print "food"[-3:-1]
oo

 >>>print "food"[-3:0]

(results in an empty line)


huh? I mean does everyone use[-3:] instead and 0 is taboo? I'm used to 
the Icon programming language where "food"[-3:0] returns --> ood


Keith Nemitz


_______________________________________________
Pythonmac-SIG maillist  -  Pythonmac-SIG at python.org
http://mail.python.org/mailman/listinfo/pythonmac-sig




More information about the Pythonmac-SIG mailing list