Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to parse a list or string into chunks of fixed length

Tags:

python

I'm really stuck on a basic question. I am trying to take a list of one item and divide it into a list of many items each with a charater length of 10. For example give a list with one item, ['111111111122222222223333333333'], the output would produce:

1111111111
2222222222
3333333333

I feel like this is super simple, but I'm stumped. I tried to create a function like this:

def parser(nub):    
    while len(nub) > 10:  
        for subnub in nub:  
            subnub = nub[::10]
            return(subnub)  
    else:  
        print('Done')

Obviously, this doesn't work. Any advice? Would using a string be easier than a list?

like image 966
drbunsen Avatar asked Jun 16 '11 12:06

drbunsen


People also ask

How do you trim a string to a specific length in Python?

Use syntax string[x:y] to slice a string starting from index x up to but not including the character at index y. If you want only to cut the string to length in python use only string[: length].


1 Answers

A related question has been asked: Slicing a list into a list of sub-lists

For example, if your source list is:

the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, ... ]

you can split it like:

split_list = [the_list[i:i+n] for i in range(0, len(the_list), n)]

assuming n is your sub-list length and the result would be:

[[1, 2, 3, ..., n], [n+1, n+2, n+3, ..., 2n], ...]

Then you can iterate through it like:

for sub_list in split_list:
    # Do something to the sub_list

The same thing goes for strings.

Here's a practical example:

>>> n = 2
>>> listo = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> split_list = [listo[i:i+n] for i in range(0, len(listo), n)]
>>> split_list
[[1, 2], [3, 4], [5, 6], [7, 8], [9]]

>>> listo = '123456789'
>>> split_list = [listo[i:i+n] for i in range(0, len(listo), n)]
>>> split_list
['12', '34', '56', '78', '9']
like image 171
machine yearning Avatar answered Sep 23 '22 09:09

machine yearning