Search code examples
pythonstringtext

Splitting a string into new lines based on specific number of characters


I would need to split a string in new lines based on the number of characters included in a list:

num_char=[14,12,7] # the list is actually longer: this is just an example
text = "Hello everyone how are you? R u ok?"

My expected output would be:

text = "Hello everyone
        how are you?
        R u ok?"

I tried as follows:

def chunks(s,mylist):
    x=0
    for n in mylist:
         print(n)
         for start in range(x,len(s),n):
                x=n
                yield s[start:start+x]

for chunk in chunks(text, num_char):
    print (chunk)

But it repeats the text for each element in num_char, not properly splitting into new lines. Can you have a look at it and let me know what I am doing wrong? Thanks


Solution

  • itertools.islice allows you to get the needed slices:

    from itertools import islice
    ...
    it_text = iter(text)  # iterator of chars
    
    for p in num_char:
        print(''.join(islice(it_text, p + 1)))
    

    Hello everyone 
    how are you? 
    R u ok?