Five. Python Slice __python

Source: Internet
Author: User

Part of the list is a very common element, now there is a set L = [' A ', ' B ', ' C ', ' D '], if the first 3 elements, the most primitive method is l[0], l[1], l[2], or with the loop out
R=[]
N=3
For I in range (n)
R.append (L)
Python provides us with a simpler way to get the slice slice operator, l[0:3], to achieve the same effect as the above, if the second and third elements are l[1:3].
If it is l[:] The equivalent of copying a new list set, L[::n] means that every n data is fetched. Change list to tuple, slice operation is identical, only slice of result also become tuple.
For the list, since Python supports l[-1] to take the penultimate element, it also supports reciprocal slices, l[-2:]=[' C ', ' D '],l[:-2]=[' A ', ' B '.

Similarly we can slice strings, string ' xxx ' and unicode string u ' xxx ' can also be considered as a list, each element is a character. Therefore, strings can also be sliced, but the result of the operation is still a string:

>>> ' ABCDEFG ' [: 3]
' ABC '
>>> ' ABCDEFG ' [-3:]
' EFG '
>>> ' ABCDEFG ' [:: 2]
' Aceg '

In many programming languages, many kinds of intercepting functions are provided for strings, but the goal is to slice the string. Python does not have an intercept function for a string, it is simple to slice one operation.

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.