Search code examples
pythonraspberry-pilcd

Split one long string by multiple delimeter in shorter string with max len


i try to send long strings to a 20x4 LCD Display on the raspberry pi, which means 20 character in 4 lines.

To keep the text readable on the lcd i want to split on

  1. whitespace
  2. Special character like ',', '.', '!', '?', etc
  3. Max line len of 20
  4. Max word len of 20

I found some code split strings by word(whitespace) but i cant get further...

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)]

In this case two words could be 'foobarfoobarfoobar foo' which is longer than 20 chars.


Solution

  • The nice textwrap module in the standard library brings you the first 90%. It splits mainly on whitespace (not on your special characters). If you really need to split on these ones as well, you can always suffix them with a whitesapce.

    import textwrap
    wrapper = textwrap.TextWrapper(width=20)
    for line in wrapper.wrap(text):
        print line, len(line)