读书人

关于list切片有关问题细节

发布时间: 2013-04-02 12:35:26 作者: rapoo

关于list切片问题细节

print "hello"[6] or 3

print "hello"[6::] or 3


两者的运行结果分别为:
1)IndexError: string index out of range

2)3
[解决办法]
s[i:j] slice of s from i to j (3)(4)
s[i:j:k] slice of s from i to j with step k (3)(5)

注释4这样写
The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty

所以不会报出错
[解决办法]
原因楼上已经说了,方括号里面一个数s[ind],不是切片,准确说是获得ind的那个元素,需要程序员自己保证ind<len(s),否则会出错.

切片需要加冒号,切片的话不会出错的,
>>> print 'hello'[6:] or 3
3

读书人网 >perl python

热点推荐