Explained on the Python website:
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