我尝试将长串发送到覆盆子pi上的20x4 LCD显示器,这意味着4行中有20个字符。
要保持lcd上的文字可读,我希望在
上拆分我发现一些代码按字(空格)分割字符串,但我无法进一步...
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个字符。
答案 0 :(得分:3)
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)
答案 1 :(得分:0)
s = "longlongstuff [...]"
n = s.split() #whitespace
n = n.split(",")
n.flatten() #not sure about this. transforms matrixes (and 3or more dimensional arrays) into one dimensional ones
n = n.split(".")
n.flatten()
#...
for i in range(len(n)):
e = n[i]
if len(e) > 20: #length longer than 20
n[i] = [e[:20],e[19:]]
n.flatten()
"\n". join(n)
应该有点工作。小psydocode
答案 2 :(得分:0)
您可以使用正则表达式在最近的单词边界处将换行符插入20个字符:
In [22]: print re.sub(r"(\b.{,20}\b)",r"\1"+"\n",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
foobarfoobarfoobar
foo
如果你想更具体或添加更多逻辑,你也可以将lambda传递给sub:
In [106]: f = lambda x: x.group(1).strip()+",\n"
In [107]: print re.sub(r"(\b.{,20}\b)", f, s).rstrip(",\n")
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,
foobarfoobarfoobar,
foo