1. 程式人生 > >python中的字串切片操作

python中的字串切片操作

Sequence[left:right:step]:

1,若step為正,則表示從索引left開始取,直到索引right為止,但不包括索引right.

如果left >= right,結果為空;

如果left預設,預設為0;

如果right預設,預設為len(Sequence);

>>> l = [0,1,2,3,4,5,6,7,8,9]
>>> l[4:4]
[]
>>> l[:4]
[0, 1, 2, 3]
>>> l[4:]
[4, 5, 6, 7, 8, 9]
2,若step為負,則表示從索引left開始取,直到索引right為止,但不包括索引right.

如果left <= right,結果為空;

如果left預設,預設為len(Sequence)-1;

如果right預設,預設為-1(好吧,我承認這個-1是我自己安排的);

>>> l[4:4:-1]
[]
>>> l[:4:-1]
[9, 8, 7, 6, 5]
>>> l[4::-1]
[4, 3, 2, 1, 0]
step預設時為1.