The meaning of a slice literally is also well understood, which is to cut something into a fragment. In other words, a slice is an operation on data that intercepts a fragment of data, a string, a list, and a tuple that support slicing.
#syntax: Action Object [start Position: End position: Step]#The default value for the start position is 0, the default value for the end position is the maximum length of the operand +1, the default value for the step is 1, the positive number is cut from left to right, and the negative is from right to left, including the start position, excluding the end position. My_str ='Hello Jonas'#intercepts the Hello character, if the default value is used, it may not be written, but the colon must be writtenRESULT_STR = My_str[:5]#Hello#intercept the last two elements of a listMy_list = [1,2,3,4,5]result_list= My_list[-2:]#[4,5]#You can also specify the step sizeMy_tuple = (1,2,3,4,5) Result_tuple= My_tuple[::2]#(1,3,5)
In addition, you can use slices to reverse-order the set:
My_list = [1,2,3,4,5]# If you need to reverse the list, you can use the built-in method of the list, but the method will change the original list my_list.reverse () # using slice inversion does not change the original list result = My_list[::-1]
You can also use slices to make shallow copies of an ordered collection (copying only the content, not the memory address, which means that the copy is a separate object):
My_list = [1,2,3,4,5= my_list[::]print(result,id (Result) = = ID (my_list)) # [1,2,3,4,5] False
Python Learning path-the slice of Python basics