首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

关于list切片有关问题细节

2013-04-02 
关于list切片问题细节print hello[6] or 3print hello[6::] or 3两者的运行结果分别为:1)IndexError:

关于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

热点排行