Ruven Guna
Ruven Guna

Reputation: 424

Split string into segments using python

I am trying to come up with a code that is able to take in a string and split it into messages with n number of characters. Each message cannot exceed n but can have less than n characters as words should not be split. For example 'This is an example message' and n=10. This code would return 'This is an' 'example' 'message'

Any suggestions on how I can approach this?

import math 

def solution(S, K):
    x = math.ceil(len(S)/K)
    y = S.split()

    lists = [[] for i in range(x)]

    for i in lists:
        while len(i) <= K:
            i.append(y[b])
            b+=1

x is the number of messages that I think is needed. Can someone explain to me how I can complete my code?

Upvotes: 0

Views: 102

Answers (1)

Draconis
Draconis

Reputation: 3461

This is what the textwrap library is for.

>>> from textwrap import wrap
>>> print(wrap('This is an example message', 10))
['This is an', 'example', 'message']

Upvotes: 1

Related Questions