Slicing operations for Python

Source: Internet
Author: User

The slice operator is a sequence name followed by a square bracket, with a pair of optional digits in the square brackets, separated by a colon. Note that this is very similar to the index operator you are using. Remember that the number is optional, and the colon is required.

The first number in the slice operator (preceded by a colon) indicates where the slice begins, and the second number (after the colon) indicates where the slice ends, and the third number (after the colon) represents the number of tile intervals . If you do not specify the first number, Python starts from the beginning of the sequence. If you do not specify a second number, Python stops at the end of the sequence. Note that the returned sequence starts at the start position and ends just before the end position. That is, the start position is contained in the sequence slice, and the end position is excluded from the slice.

This shoplist[1:3] returns a slice that contains two items, starting at position 1, including position 2, but stopping a sequence slice at position 3. Similarly, shoplist[:] a copy of the entire sequence is returned. Shoplist[::3] Return position 3, position 6, Position 9 ... The sequence slice.

You can make slices with negative numbers. negative numbers are used at the beginning of the end of the sequence . For example, a shoplist[:-1] sequence slice that contains all items except the last item is returned, and shoplist[::-1] returns the reverse sequence slice. Use the Python interpreter to interactively try out different slices of the specified combination, i.e. you can see the results immediately at the prompt. The magic of sequences is that you can access tuples, lists, and strings in the same way. :

Example:

>>> str1 = ' i2sl54ovvvb4e3bferi32s56h; $c 43.sfc67o0cm99 '

>>> Str1[::3]

' Ilovefishc.com '

Slicing operations for Python

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.