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.
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!
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)