First, you need to understand how each of the elements in N = '1234567890' is indexed. If you want to access "1"
, you can use N[0]
. "2"
with N[1]
. And so on till N[9]
which equals to "0"
.
Your goals is to create things like
slice1 = '12345'
slice2 = '23456'
slice3 = '34567'
Let's take a look at slice1
with both values and how to access then via N
'1' '2' '3' '4' '5'
N[0] N[1] N[2] N[3] N[4]
Now we turn to list slices. Given a list l
. One can select a part of it by specifying the start
and end
, two indeces like l[start:end]
.
Note that l[start:end]
will select elements
l[start], l[start+1], ..., l[end-1]
Yes. l[end]
is not selected. The selection will include the starting index but exclude the ending index.
Back to the slice1
example, how do you select '12345'
? From the discussion above, we know we want indeces from 0 to 4. Thus, we need to put N[0:5]
because as mentioned, N[5]
would not be included in this way.
Given this practice, you can now write a for loop to yield slice1
, slice2
, and slice3
in a row.
We can do it like
gap = 5
slices = []
for i in range(3):
slices[i] = N[i:i+gap]
# slices will be ["12345", "23456", "34567"]
# or
slice1 = N[0:5]
slice2 = N[1:6]
slice3 = N[2:7]
We did it by defining a variable gap
. There is always a gap of 5 between the starting index and the ending index because the slices we want are of length 5. With some more observation: if a starting index is i
and then the ending index should be i + gap
. We increment one at a time to get a new slice.
Note that I only introduce one way to do list slicing that matches your particular need in this example. You can find more usage in this question Understanding Python's slice notation