对于任何可迭代的对象(例如字符串,列表等),Python允许您切片并返回其数据的子字符串或子列表。
切片格式:
iterable_name[start:stop:step]
哪里,
start是切片的第一个索引。默认为0(第一个元素的索引)
stop片的最后一个索引之后的一个。默认为len(iterable)
step 是步长(下面的示例可以更好地说明)
例子:
a = "abcdef" a # "abcdef" # 与a [:]或a [::]相同,因为它对所有三个索引使用默认值 a[-1] # "f" a[:] # "abcdef" a[::] # "abcdef" a[3:] # "def" (from index 3, to end(defaults to size of iterable)) a[:4] # "abcd" (from beginning(default 0) to position 4 (excluded)) a[2:4] # "cd" (from position 2, to position 4 (excluded))
此外,上述任何一种都可以与定义的步长一起使用:
a[::2] # "ace" (every 2nd element) a[1:4:2] # "bd" (from index 1, to index 4 (excluded), every 2nd element)
索引可以为负,在这种情况下,它们是从序列末尾开始计算的
a[:-1] # "abcde" (from index 0 (default), to the second last element (last element - 1)) a[:-2] # "abcd" (from index 0 (default), to the third last element (last element -2)) a[-1:] # "f" (from the last element to the end (default len())
步长也可以为负,在这种情况下,切片将以相反的顺序遍历列表:
a[3:1:-1] # "dc" (from index 2 to None (default), in reverse order)
此构造对于反转可迭代项很有用
a[::-1] # "fedcba" (from last element (default len()-1), to first, in reverse order(-1))
请注意,对于否定步骤,默认end_index值为None(请参阅http://stackoverflow.com/a/12521981)
a[5:None:-1] # "fedcba" (this is equivalent to a[::-1]) a[5:0:-1] # "fedcb" (from the last element (index 5) to second element (index 1)