Python Learning path-the slice of Python basics

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.