Creating a newline in a string after 20 characters at the end of a word, Python

Question:

I’ve tried multiple things at this point, but can’t get my head around my own problem.
At any point before the 20th character in a string (the closer to 20 the better), but it must be after a space, I need my Python code to automatically insert a newline.

For example:

string = "A very long string which is definately more than 20 characters long"

I would need a "n" inserted in place of the space after the word string, (the 19th character), and then again after definitely (the 20th character after the previous linebreak)

Essentially, I need a sentence to span across a 20 character screen, and break off at the end of a word if it nears the edge.

A possible concept might involve searching after the 15th character for a space, and breaking off there? I’m not sure how this would be implemented there.

Hopefully this makes sense!

Asked By: Taras Zagajewski

||

Answers:

There may be better ways to do this but this seems to work:-

s = "A very long string which is definately more than 20 characters long"
offset = 0
try:
    while True:
        p = s.rindex(' ', offset, offset + 20)
        s = s[:p] + 'n' + s[p + 1:]
        offset = p
except ValueError:
    pass

print(s)
Answered By: user2668284

This code could be improved but you can start with something like this:

def until_x(string: str, x : int = 20) -> str:
     """
     params:
     string <str>: a str object that should have line breaks.
     x <int>: the max number of characters in between the line breaks.
     
     return:
     a string which has line breaks at each x characters.
     
     usage:
     >>> str_ = 'A very long string which is definately more than x characters long'
     >>> until_x(str_)  # default value of x is 20
     'A very long string nwhich is definately nmore than x ncharacters long '
     >>>
     >>>until_x(str_, 30)
     'A very long string which is ndefinately more than x ncharacters long '
     >>>
     """
     lst = string.split()
     line = ''
     str_final = ''
     for word in lst:
         if len(line + ' ' + word) <= x:
             str_final += word + ' '
             line += word + ' '
         else:
             str_final += 'n' +  word + ' '
             line = word + ' '
     return str_final
Answered By: Jailton Silva

You can use Python built-in textwrap.wrap function:

>>> from textwrap import wrap
>>> string = 'A very long string which is definately more than 20 characters long'
>>> print('n'.join(wrap(string, 20)))
A very long string
which is definately
more than 20
characters long
Answered By: Yogev Neumann
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.