Python 程序对元组进行切片

编写一个 Python 程序来使用示例执行元组切片。元组切片具有开始位置、结束位置和步长。元组切片从开始位置开始,直到结束位置,但不包括结束位置,其语法为:

TupleName[starting_position:ending_position:steps]

如果省略开始位置,则元组切片从零索引位置开始。类似地,如果跳过结束位置,切片将一直到末尾。如果同时省略开始和结束位置,元组切片将复制所有元组项。

在此 示例 中,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)
Program to Slice a Tuple

元组切片中的负值将从右侧开始切片。例如,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')