0

I have an N length string of digits or a number. I then turn it into a list to iterate over the digits. I want to slice the list into 5 digit blocks that look like so:

N = '1234567890'

slice1 = '12345'
slice2 = '23456'
slice3 = '34567'

and so on...

I am having trouble finding code examples of this for python, specifically slicing and for loops. Any help would be appreciated, thanks.

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96

6 Answers6

1

You can create a list of using list comprehension.

N = '1234567890'

all_slices = [N[i:i+5] for i in range(len(N)-4)]
James
  • 32,991
  • 4
  • 47
  • 70
0

Just do this

n = '1234567890'
for i in range(len(n)):
   print(n[i:i+5])

this should do the trick. But I need to say that it is hard to believe you actually search the Internet because it is a frequently asked question...

UPDATE

if you want to use the different slices you can try this:

n = '1234567890'

ar= [None]*len(n)

for i in range(len(n)):
   if len(n[i:i+5]) == 5:
      ar[i] = n[i:i+5]
   else:
      del ar[i:-1]
      del ar[-1]
      break

for i in ar:
   print(i)

So what happens here is:

  • You make an array that has the size of the string and fill them with None values
  • You check if the remaining size of the string is 5 pieces long
    • if so you slice the string in pieces of 5 with [i:i+5] and do the check again for the next slices
    • if not you delete the remaining None values and break the loop
Seppe Mariën
  • 355
  • 1
  • 13
  • When searching for the terms "For loop/looping over/iterating over slices/arrays/lists" I was having a trouble find the term "sliding/rolling window" so that's when I deferred to this site for help. Thanks for the solution and explanation. –  Jan 04 '18 at 02:44
  • No problem :) Please accept answer if you find this answer to be the solution – Seppe Mariën Jan 05 '18 at 17:44
0

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

Tai
  • 7,684
  • 3
  • 29
  • 49
0

You can also try converting N to a list beforehand, and popping off the first character each iteration, until the list is less than length 5. Then you could just take the first five characters each iteration.

Here is an example using collections.deque:

from collections import deque
from itertools import islice

N = '1234567890'
items = deque(N)
size = 5

result = []
while len(items) >= size:
    result.append("".join(islice(items, 0, size)))
    items.popleft()

print(result)

Which Outputs:

['12345', '23456', '34567', '45678', '56789', '67890']

Note: itertools.islice was used here to slice the deque object. You could also use list(items)[:5], but this creates an extra copy of the list everytime.

RoadRunner
  • 25,803
  • 6
  • 42
  • 75
0

Using a dict comprehension:

N = '1234567890'
slices = {'slice'+str(i+1): N[i:i+5] for i in range(len(N)-4)}

Usage:

slice1 = slices['slice1']
slice2 = slices['slice2']
slice3 = slices['slice3']

and so on...

srikavineehari
  • 2,502
  • 1
  • 11
  • 21
0

As simple as that:-

from collections import deque
N = '1234567890'
m = deque(N)
for i in range(len(m)-4):
    print N[i:i+5]
#output as you expected
Narendra
  • 1,511
  • 1
  • 10
  • 20