Search code examples
pythonword-wrap

How does one split up a non-explicitly given string into two or more lines?


I'm currently working with a Python bot that outputs an image with text, but I've found out that oftentimes the text is too long to be presented. Thus, I've decided to split up the string into two lines so it can fit into my image. I am utilizing Pillow 5.1 for image manipulaton.

I am a neophyte to Python programming, and I've tried to search how to split up a Python string into two or more lines. Unfortunately, all of the results seem to only deal with strings explictly given(i.e 'string').

print("Ababoubian wisdom!")
ababou2 = ababou() #returns a string, how to split into two lines?
if("Ababou" in ababou2):
    ababou2 = ababou()
font = ImageFont.truetype("Arial.ttf", 14)
img = Image.new('RGB', (300, 200), color = (random.randint(0, 255),random.randint(0, 255), random.randint(0, 255)))
d = ImageDraw.Draw(img)
d.text((0, 0), ababou2, font=font) #draws text

Actual results

Expected results: The text should wrap around to the next line.


Solution

  • I'm not sure a text wrapper could help in your case since you need to draw each line separately.

    Seems like you should calculate the maximum length of chars in a single line, then do:

    ababou2 = ababou() # Whats the point of assigning the same value twice? 
                       # does ababou() returns a different value each time?
    if "Ababou" in ababou2:
        ababou2 = ababou()
    
    res_text = list()
    ababou2 = ababou2.split(' ') # Splits the string by space\ ' ', to a list of strings 
    curr_txt = ''
    for word in ababou2:
        if len(curr_txt) < MAX_CHARS_PER_LINE: # This you need to figure out
            curr_txt += ' '  + word
        else:
            res_text.append(curr_txt)
            curr_txt = word
    
    font = ImageFont.truetype("Arial.ttf", 14)
    img = Image.new('RGB', (300, 200), color = (random.randint(0, 255),random.randint(0, 255), random.randint(0, 255)))
    d = ImageDraw.Draw(img)
    y = 0
    for line in res_text:
        d.text((0, y), line, font=font) #draws text
        y += SINGLE_ROW_SPACE # Figure out what is the distance between two rows.