Python中的块字符串,不会破坏单词

sec*_*ica 2 python raspberry-pi

我有这个代码,用于在20x2 LCD显示屏上显示一些文字:

#!/usr/bin/python

LCDCHARS = 20
LCDLINES = 2

def WriteLCD(text_per_LCD):
    chunked = (text_per_LCD[i:LCDCHARS+i] for i in range (0, len(text_per_LCD), LCDCHARS))
    count_l = 0
    for text_per_line in chunked:
        # print will be replaced by actual LCD call
        print (text_per_line)
        count_l += 1
        if count_l >= LCDLINES:
            # agree to lose any extra lines
            break

WriteLCD("This text will display on %s LCD lines" % (LCDLINES))
Run Code Online (Sandbox Code Playgroud)

将输出示例字符串

This text will displ
ay on 2 LCD lines
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能分割字符串而不会破坏字词?即使第二行变得更长并且不显示.

我在javascript部分读了一个类似的问题,在ruby部分读了另一个,但是我无法将给定的答案翻译成我的Python案例.

Dan*_* D. 9

使用textwrap模块:

>>> textwrap.wrap("This text will display on 3 LCD lines", 20)
['This text will', 'display on 3 LCD', 'lines']
Run Code Online (Sandbox Code Playgroud)