5

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!

0

3 Answers 3

19

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']
1
  • You are aweseome! Thank you.
    – spky
    Commented Aug 31, 2013 at 19:19
3

As DSM suggested, look at textwrap. If you prefer to stick with regular expressions, the following will get you part of the way there:

In [10]: re.findall(r'.{,16}\b', text)
Out[10]: 
['Hello, this is ',
 'an example of ',
 'text shown in ',
 'the scrolling ',
 'display. Bla, ',
 'bla, bla',
 '']

(Note the missing exclamation mark and the empty string at the end though.)

2
  • Do you want my honest answer? Better not stick with regex :) But thank you anyway.
    – spky
    Commented Aug 31, 2013 at 19:21
  • @spky: Actually, I agree with you on this :)
    – NPE
    Commented Aug 31, 2013 at 19:25
2

Using regex:

>>> text = 'Hello, this is an example of text shown in the scrolling display. Bla, bla, bla!'
>>> pprint(re.findall(r'.{1,16}(?:\s+|$)', text))
['Hello, this is ',
 'an example of ',
 'text shown in ',
 'the scrolling ',
 'display. Bla, ',
 'bla, bla!']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.