我尝试将长字符串发送到树莓派上的 20x4 LCD 显示器,这意味着 4 行 20 个字符。
为了让液晶显示器上的文字可读,我想拆分
- 空格
- ',', '.', '!', '?' 等特殊字符
- 最大行长度为 20
- 最大字数为 20
我发现了一些按单词(空格)拆分字符串的代码,但我无法进一步...
s = "This is a very long string with many many many many and many more sentences and there is not one character that i can use to split by, just by number of words 1 2 3 12° C 3, ,5 ,6 .7 5 "
l = s.split()
n = 5
[' '.join(l[x:x+n]) for x in range(0, len(l), n)]
在这种情况下,两个单词可以是 'foobarfoobarfoobar foo',它的长度超过 20 个字符。
nice textwrap
module in the standard library为您带来前90%。它主要根据空格(而不是您的特殊字符)进行分割。如果您确实也需要对这些进行拆分,您始终可以在它们后面加上一个 whitesapce。
import textwrap
wrapper = textwrap.TextWrapper(width=20)
for line in wrapper.wrap(text):
print line, len(line)
我是一名优秀的程序员,十分优秀!