Python note eight (slice)

Source: Internet
Author: User

One, slice

First we have to remember that the objects that can be used for slicing in Python are lists, tuples, and strings.

Slicing is a simple and practical way to choose what we want directly from a list, a tuple, or a string.

>>> L = list (range)>>>1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 1  8, +]>>> l[0:101, 2, 3, 4, 5, 6, 7, 8, 9]>>> l[:101, 2, 3, 4, 5, 6, 7, 8, 9]>>> l[0:10:22, 4, 6, 8]

>>> l[:] #取出所有的数
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

As shown in the code above, a 0-20 list is generated, and we can take the values we want directly from the list by slicing.

  Note that when you take 0-9 of these 10 numbers, we need to set the end position of the slice to 10, but not the value of 10. It can also be omitted when the starting position of the slice is 0.

>>> l[-1]19>>>>>> l[-10: 0][]>>> l[-10: [10, 11, 12, (+, +, +, +, +)>>>

Slices can also be counted backwards, and the last number's index is-1.

When you want to remove the last 10 digits, the end position of the slice cannot be written 0 and must be empty.

  

Python note eight (slice)

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.