I want to display some text on a scrolling display with a width of 16 characters. To improve readability I want to flip through the text, but not by simply splitting every 16. character, I rather want to split on every ending of a word or punctuation, before the 16 character limit exceeds..
Example:
text = 'Hello, this is an example of text shown in the scrolling display. Bla, bla, bla!'
this text shall be converted in a list of strings with 16 characters maximum
result = ['Hello, this is ', 'an example of ', 'text shown in ', 'the scrolling ', 'display. Bla, ', 'bla, bla!']
I started with the regex re.split('(\W+)', text)
to get a list of every element (word, punctuation), but I fail combining them.
Can you help me, or at least give me some hints?
Thank you!
I'd look at the textwrap module:
>>> text = 'Hello, this is an example of text shown in the scrolling display. Bla, bla, bla!'
>>> from textwrap import wrap
>>> wrap(text, 16)
['Hello, this is', 'an example of', 'text shown in', 'the scrolling', 'display. Bla,', 'bla, bla!']
There are lots of options you can play with in the TextWrapper, for example:
>>> from textwrap import TextWrapper
>>> w = TextWrapper(16, break_long_words=True)
>>> w.wrap("this_is_a_really_long_word")
['this_is_a_really', '_long_word']
>>> w = TextWrapper(16, break_long_words=False)
>>> w.wrap("this_is_a_really_long_word")
['this_is_a_really_long_word']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With