Python Advanced Features: Slice (slice) flexible specified range

Source: Internet
Author: User

Explained on the Python website:

  • class slice ( stop )

  • classslice(Start,Stop[,Step])

Return a Slice object representing the set of indices specified by range (start, stop, step). The start and step arguments default to None. Slice objects has read-only data attributes start, stop and step which merely return the argument values (or their defaul T). They has no other explicit functionality; However they is used by numerical Python and all third party extensions. Slice objects was also generated when extended indexing syntax was used. For Example:a[start:stop:step] or a[start:stop, I]. See Itertools.islice () for a alternate version that returns an Itera Tor.


I. General specified Range method

#将数字填入L

L = []; #list
n = 1;
While N <= 99:
L.insert (0, N);
n = n + 1;
Print L;


#take N in head
n = 10
For I in range (n):
Print I, ":", l[i];


Second, the Slice way

L = []; #list
n = 1;
While n <=:
L.insert (0, N);
n = n + 1;


#slice
# #follow:Print "l[0:10]:", l[0:10]; #从第0位开始, end of 10th place
Print "l[:10]:", l[:10];# = L[0:10]
Print "L[::2]:", l[::2]; # = L[0:100:2] Every 2 out of 1
Print "L[-2:]", l[-2:]; # start from left to right, second to last
Print "l[-2:-1]", l[-2:-1];# Start from left to right, Count second, end first

Print "l[:-90]:", l[:-90];

print ';


string = ' abcdef '
print ' string:%s '%string;
print ' string[:3]: ', string[:3];
print ' string[::2]: ', string[::2];


As can be seen, slice is more concise than the cycle.

Python Advanced Features: Slice (slice) flexible specified range

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.