寫一個 Python 程序,用一個例子來執行元組切片。元組切片有開始位置、結束位置和要跳轉的步驟。元組的切片從開始位置開始,一直到結束位置,但不包括結束位置。這個元組切片的語法是
TupleName[starting_position:ending_position:steps]
如果省略起始位置,元組切片從零索引位置開始。同樣,如果您跳過 end _ position,切片將轉到元組末尾。如果您忘記了開始和結束,元組切片將複製所有元組項。在這個 Python 示例中,numTuple[2:6]在索引位置 2(物理位置是 3)開始元組切片,在 5 結束。
# Tuple Slice
numTuple = (11, 22, 33, 44, 55, 66, 77, 88, 99, 100)
print("Tuple Items = ", numTuple)
slice1 = numTuple[2:6]
print("Tuple Items from 3 to 5 = ", slice1)
slice2 = numTuple[3:]
print("Tuple Items from 4 to End = ", slice2)
slice3 = numTuple[:7]
print("Tuple Items from Start to 6 = ", slice3)
slice4 = numTuple[:]
print("Tuple Items from Start to End = ", slice4)
元組切片中的負值將從右側開始切片。例如,numTuple[-5:-2]從元組右側的第五個位置開始切片,並從右側上升到第二個位置。在最後一個例子中,numTuple[1:7:2]從 1 開始元組切片,在 6 結束,每隔一秒複製一項。
# Tuple Slice
numTuple = (11, 22, 33, 44, 55, 66, 77, 88, 99, 100)
print("Tuple Items = ", numTuple)
slice1 = numTuple[-5:-2]
print("Tuple Items = ", slice1)
slice2 = numTuple[-4:]
print("Last Four Tuple Items = ", slice2)
slice3 = numTuple[:-5]
print("Tuple Items upto 5 = ", slice3)
slice4 = numTuple[1:7:2]
print("Tuple Items from 1 to 7 step 2 = ", slice4)
Tuple Items = (11, 22, 33, 44, 55, 66, 77, 88, 99, 100)
Tuple Items = (66, 77, 88)
Last Four Tuple Items = (77, 88, 99, 100)
Tuple Items upto 5 = (11, 22, 33, 44, 55)
Tuple Items from 1 to 7 step 2 = (22, 44, 66)
切割字元串元組的 Python 程序
# Tuple Slice
strTuple = tuple("Tutotial Gateway")
print("Tuple Items = ", strTuple)
slice1 = strTuple[2:10]
print("Tuple Items from 3 to 9 = ", slice1)
slice2 = strTuple[-4:]
print("Last Four Tuple Items = ", slice2)
slice3 = strTuple[2:12:2]
print("Tuple Items from 3 to 9 step 2 = ", slice3)
slice4 = strTuple[::2]
print("Every second Tuple Item = ", slice4)
Tuple Items = ('T', 'u', 't', 'o', 't', 'i', 'a', 'l', ' ', 'G', 'a', 't', 'e', 'w', 'a', 'y')
Tuple Items from 3 to 9 = ('t', 'o', 't', 'i', 'a', 'l', ' ', 'G')
Last Four Tuple Items = ('e', 'w', 'a', 'y')
Tuple Items from 3 to 9 step 2 = ('t', 't', 'a', ' ', 'a')
Every second Tuple Item = ('T', 't', 't', 'a', ' ', 'a', 'e', 'a')
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/258281.html