Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Wrap text in list

I am trying to write a function which takes some text and a list, and then if the last element in the list is small enough so that it can append text to that last element and still have less than 10 chars, then do it. Otherwise, append it to the list separately. The problem I'm having is that if text is for example 25 char long.

For example,

l = ["12345678", "123456789"]

>>> a("a", l)
["12345678", "123456789a"]

>>> a("123456789123456789123", l)
["12345678", "1234567891", "2345678912", "3456789123"]

This is what I have so far

def a(st, lst):
    last = 10 - len(lst[-1])

    if last < len(st):
        lst[-1] += st[:last]
        lst.append(st[last:])
    else:
        lst[-1] += st

1 Answers

The problem is that st (in your given function) can be arbitrary long and thus you have to add an arbitrary amount of elements. Now in case something is arbitrary, that usually calls for a loop (for or while).

The algorithm itself consists out of two phases: in the fist phase we check how much space is left in the last element of lst. We fill up that element with (a part of) st. You can do this with:

left = 10-len(lst[-1])
lst[-1] += st[:left]

Note that you do not need an if here: in case there is no space left, it will add no characters, and furthermore if there are too few characters in st the slicing will simply return a substring.

Now we only need to add the remaining characters in chunks of 10 to lst. We can do this by writing a for loop that starts at left (since we can omit the first left characters) and makes jumps of 10 positions until it hits the end of the string:

for i in range(left,len(st),10):
    # ... do something
    pass

It is quite clear what we have to do: add slices st[i:i+10] to the lst. So we turn the for loop into:

for i in range(left,len(st),10):
    lst.append(st[i:i+10])

finally we only have to return the lst. Putting it all together we got:

def a(st, lst):
    # phase 1
    left = 10-len(lst[-1])
    lst[-1] += st[:left]

    #phase 2
    for i in range(left,len(st),10):
        lst.append(st[i:i+10])

    return lst

Note that this solution operates on the given list. In case you want to make a copy, you can add one line:

def a(st, lst):
    # make copy
    lst = list(lst)

    # phase 1
    left = 10-len(lst[-1])
    lst[-1] += st[:left]

    #phase 2
    for i in range(left,len(st),10):
        lst.append(st[i:i+10])

    return lst
like image 158
Willem Van Onsem Avatar answered Jul 13 '26 10:07

Willem Van Onsem