python中對切片的理解

2021-10-20 09:55:11 字數 1464 閱讀 9120

字串還支援 切片。索引可以提取單個字元,切片 則提取子字串:

>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)

'py'

>>> word[2:5] # characters from position 2 (included) to 5 (excluded)

'tho'

注意,輸出結果包含切片開始,但不包含切片結束。因此,s[:i] + s[i:]總是等於s

>>> word[:2] + word[2:]

'python'

>>> word[:4] + word[4:]

'python'

切片索引的預設值很有用;省略開始索引時,預設值為 0,省略結束索引時,預設為到字串的結尾:

>>> word[:2]   # character from the beginning to position 2 (excluded)

'py'

>>> word[4:] # characters from position 4 (included) to the end

'on'

>>> word[-2:] # characters from the second-last (included) to the end

'on'

還可以這樣理解切片,索引指向的是字元 之間 ,第乙個字元的左側標為 0,最後乙個字元的右側標為 n ,n 是字串長度。例如:

+---+---+---+---+---+---+

| p | y | t | h | o | n |

+---+---+---+---+---+---+

0 1 2 3 4 5 6

-6 -5 -4 -3 -2 -1

第一行數字是字串中索引 0…6 的位置,第二行數字是對應的負數索引位置。i 到 j 的切片由 i 和 j 之間所有對應的字元組成。

對於使用非負索引的切片,如果兩個索引都不越界,切片長度就是起止索引之差。例如,word[1:3]的長度是 2。

索引越界會報錯:

>>> word[42]  # the word only has 6 characters

traceback (most recent call last):

file "", line 1, in indexerror: string index out of range

但是,切片會自動處理越界索引:

>>> word[4:42]

'on'

>>> word[42:]

''

python切片的物件 Python切片物件和

python中是否存在某種內部機制,它以不同的方式處理傳遞給 getitem 的引數,並自動將start stop step構造轉換為片?在 這是我的意思class exampleclass object def getitem self,args return args def call self...

徹底理解Python切片

徹底理解python切片 wyf部落格 list insert ind,value 在ind元素前面插入value 首先對ind進行預處理 如果ind 0,則ind len a 這樣一來ind就變成了正數下標 預處理之後,當ind 0時,ind 0,相當於頭部插入 當ind len a 時,ind ...

Python中的切片

1切片 切片就是取出集合中的一部分元素。當然集合不能是無序的,因為他是按照索引去取值的 例 range 函式可以建立乙個數列 取出 1.前10個數 2.3的倍數 3.不大於50的5的倍數。l range 1,101 print l 10 print l 2 3 print l 4 50 5 輸出結果...