Home > other >  Freshman consult Python slice
Freshman consult Python slice

Time:11-30

Set s='abcdefg, s [0:5: - 1) and s [: 5: - 1), s [0-0: - 1) and s [0... 1] s [: 0, 1] and s [: : - 1] results are different, why is this?

CodePudding user response:

Learn programming is reading a book now? Google is not in the meeting, baidu also need not?

https://www.jianshu.com/p/15715d6f4dad

CodePudding user response:

Slicing operation object [start_index: end_index: step]
Analysis steps:
1, step for regular positive section, negative reverse slice;
2, if start_index and end_index are digital
(1) positive start_index when slice, pointing to the element must be on the left side of the point end_index elements, otherwise the result is empty.
(2) reverse start_index when slice, pointing to the element must be on the right side of the point end_index elements, otherwise the result is empty.
3, if start_index omit, represents slices from its starting endpoint, namely if the step is positive, start_index -> s [0]; If the step is negative, start_index -> s [len (s) - 1);
4, if end_index omit, represents the termination of the endpoint to stop slicing, and pointed out by section contains end_index elements, namely if the step is positive, end_index -> s [len (s) - 1] (including s [len (s) - 1)); If the step is negative, start_index [0] -> s (including s [0]),
Based on the analysis of the above criteria:
 
S='abcdefg'

Print (s] [0:5: - 1) # reverse, beginning a, f, end result is an empty
Print (s) [: 5: - 1] # reverse, starting point g, f, end result is g
Print (s] [0-0: - 1) # reverse, a starting point, the end point a, the result is an empty
Print (s [0... 1]) # reverse, a starting point, the end point a (including), the result is a
Print (s] [: 0: - 1) # reverse, beginning, end point a, the result is g gfedcb
Print (s] [: : - 1) # reverse, starting point g, end a (including), the result is gfdecba
  • Related