How to use slicing in Python?

In Python, slicing is an operation used to retrieve a subsequence from a sequence (such as a string, list, tuple, etc.). Slicing is done using the syntax [start:stop:step], where start represents the starting position (inclusive), stop represents the ending position (exclusive), and step represents the increment (default is 1).

Below are some examples of using slices:

  1. Get the sublists from the list.
lst = [1, 2, 3, 4, 5]
sub_lst = lst[1:4]  # 获取索引1到索引3的子列表,结果为[2, 3, 4]
  1. Certain parameters can be omitted when slicing, such as not specifying start, which defaults to 0; not specifying stop, defaults to the length of the sequence; not specifying step, defaults to 1.
lst = [1, 2, 3, 4, 5]
sub_lst = lst[2:]  # 获取从索引2到末尾的子列表,结果为[3, 4, 5]
sub_lst = lst[:3]  # 获取从起始位置到索引2的子列表,结果为[1, 2, 3]
sub_lst = lst[::2]  # 获取从起始位置到末尾,步长为2的子列表,结果为[1, 3, 5]
  1. Negative numbers can be used to count from the end of the sequence, for example, -1 represents the last element, -2 represents the second to last element, and so on.
lst = [1, 2, 3, 4, 5]
sub_lst = lst[:-2]  # 获取从起始位置到倒数第三个元素(不包含)的子列表,结果为[1, 2, 3]
sub_lst = lst[-2:]  # 获取倒数第二个元素到末尾的子列表,结果为[4, 5]
  1. Slicing can also be used for sequence types like strings and tuples.
txt = "Hello, World!"
sub_txt = txt[7:]  # 获取从索引7到末尾的子字符串,结果为"World!"

Here are some common ways to use slicing, which you can use based on your specific needs and sequence types.

bannerAds