Python slices and range of instructions

  • 2020-04-02 09:47:48
  • OfStack

Understand the basic usage of slicing:

The first thing to understand is that iterable objects, in positive order, start at 0, and in negative order, in negative order, start at -1.
> > > Astring = 'Hello world'
> > > Astring [2-0]
'He'
> > >
It can be seen that, in this case, given a starting position and a ending position for the slice operation, the contents between the starting position (including the starting position) and the ending position (excluding the ending position) are displayed.

In the case of a negative index, it is similar, as long as the contents of the termination position are determined:

> > > Astring [0, 1]
'Hello worl'
> > >

> > > astring
'Hello world'
> > > Astring [0:1]
'Hello world'
> > > Astring [0: : 2)
'Hlowrd'
> > > Astring [0: : 3]
'Hlwl'
> > > Astring [0: : 4)
'Hor'
> > >
In the case of three parameters, the first starting position, the second is the ending position, and the third is the step size.

Test procedures:
First, understand the meaning of slicing, as shown below
> > > S = "abcde"
> > > S [: 0]
' '
> > > S [0:]
"Abcde"
> > > S [1]
'bcde'
> > > S / 2:
'the cde'
> > > S / : 3
"ABC"

Understand the basic usage of range() :

Test procedure 1:

> > > Range (1,5) # outputs results from 1 to 5. Including the head, not including the tail.
[1, 2, 3, 4]
> > > Range (1,5,2) # outputs the result from 1 to 5 with an interval of 2. Including the head, not including the tail.
[1, 3]
> > > Range (5) # outputs the result from 0 to 5. The default starting and ending is 0. Including the head, not including the tail.
[0, 1, 2, 3, 4]


Test procedure 2:

> > > S = "abcde"
> > > I = 1
> > > For I in range(-1,-len(s),-1): # output
.         Print the s [, I]
.
The abcd
ABC
ab
a.

Test procedure 3:

> > > S = "abcde"
> > > For I in range(len(s),0,-1): # output
.         Print the s [, I]
.
abcde
The abcd
ABC
ab
a.


Test procedure 4:

> > > S = "abcde"
> > > For I in [None] + range(-1,-len(s),-1): # use None as the output of the index value
.         Print the s [, I]
.
abcde
The abcd
ABC
ab
a.

In addition, range can directly assign a value to list variable:
Elements = range (0, 6)


Related articles: