gpt4 book ai didi

python - 用最大 len 的较短字符串中的多个定界符拆分一个长字符串

转载 作者:太空宇宙 更新时间:2023-11-04 00:55:16 24 4
gpt4 key购买 nike

我尝试将长字符串发送到树莓派上的 20x4 LCD 显示器,这意味着 4 行 20 个字符。

为了让液晶显示器上的文字可读,我想拆分

  1. 空格
  2. ',', '.', '!', '?' 等特殊字符
  3. 最大行长度为 20
  4. 最大字数为 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)

关于python - 用最大 len 的较短字符串中的多个定界符拆分一个长字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35433920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com