-1

I have list of strings list1 = ['There', 'are two', 'goats on the bridge']

I need to find a way such that each time there are no more than 10 chars in a string. if so I need to break that.

list2 = ['There', 'are two', 'goats on ','the bridge']. So this should be around or about 10, somewhat what readlines would be doing.

Thanks -Megha

Megha Bhamare
  • 77
  • 1
  • 10
  • I have referred to https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks but this isn't what i want to do. – Megha Bhamare Sep 20 '19 at 04:47

1 Answers1

0

The following simply splits each element into subelements of no more than k = 10 chars:

k = 10
[x[i:i+k] for x in list1 for i in range(0, len(x), k)]

Result:

['There', 'are two', 'goats on t', 'he bridge']



If you want to split at spaces into k = 10 plus/minus t = 2 characters, you'll need a slightly more complex approach:
from functools import reduce
import operator

def split_about_k(s, k=10, t=1):
    """split s at spaces into k +/- t sized subtsrings"""
    i = 0
    while i < len(s)-k:
        j = s.rfind(' ', i+k-t, i+k+t)
        if j < 0:
            yield s[i:i+k]
            i = i + k
        else:
            yield s[i:j]
            i = j + 1
    yield s[i:]


reduce(operator.concat, [list(split_about_k(x, 10, 2)) for x in list1])

Result:

['There', 'are two', 'goats on', 'the bridge']
Stef
  • 28,728
  • 2
  • 24
  • 52
  • thanks for this help. As I am still newbie to this, I have another issue, that I need to make this a matrix [['There'] ,['are two'], ['goats on'], ['the bridge']] where each is list1[i] is less than 10. – Megha Bhamare Sep 20 '19 at 10:43
  • 1
    like `[[x] for x in ['There', 'are two', 'goats on', 'the bridge']]`? – Stef Sep 20 '19 at 10:55