This is a function I just wrote that tries to condense a set of strings into grouped lines. It actually works, but looks ugly. Is there a better way to achieve the same thing?
Take 4 filtering empty strings first and dropping the if line
on the final yield
def mergeToLines(strings, length=40, sep=" "):
strs = (st for st in sorted(strings, key=len, reverse=True) if st)
line = strs.next()
for s in strs:
if (len(line) + len(s) + len(sep)) >= length:
yield line
line = s
else:
line += sep + s
yield line
The idea is that it takes a bunch of strings, and combines them into lines about as long as lineLength
. Each line has one or more of the original strings in it, but how many isn't clear until I actually get to slotting them in. Also, note that if a single entry in the list is longer than lineLength
, it's still added as its own line (dropping elements is not an option here).
if line:
is redundant unless you have empty strings instrings
. If you do have empty strings, you probably should filter out all of them earlier on. – Janne Karila Apr 26 at 6:36