0

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?

1
  • What have you tried so far? Commented Jan 13, 2019 at 2:37

1 Answer 1

1

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']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.