Jahongir Rahmonov Jahongir Rahmonov - 10 months ago 48
Python Question

Split by size of characters but include words entirely in Python regex

There is a task in Codefights which says given a feedback and the size of the screen, splits the feedback into lines so that:

  • each token (i.e. sequence of non-whitespace characters) belongs to one of the lines entirely;

  • each line is at most size characters long;

  • no line has trailing or leading spaces;

  • each line should have the maximum possible length, assuming that all lines before it were also the longest possible.

The requirement is that it should be solved with one line only.

I believe
should help and I tried this:

re.split(r'(?<=.{8})\s', "This is an example feedback", re.I)

to get this:

['This is an', 'example', 'feedback']

instead of:

["This is", "an", "example", "feedback"]

Obviously it does not satisfy a couple of conditions.

Just a hint toward what regex concept could help here would be awesome.

Thank you.

vks vks
Answer Source

Instead of split you can use findall.See demo.