We need to display some “preview text” from a larger string that can be, at most, ‘n’ characters long. Unfortunately, I couldn’t find an existing module on PyPi that handles this.
I’m hoping to do a proper solution. While my quick & dirty solution below works, it’s not that efficient — lots of constant comparisons. Does anyone have an idea on how to improve? I tried a regex, but gave up after 20 minutes.
The kludgy solution I came up with is good enough for most needs, I just know this could be done faster and more concisely – and I’d love to know how.
sample = "This is a sample string and I would like to break it down by words, without exceeding max_chars."
def clean_cut( text , max_chars ):
rval = []
words = text.split(' ')
for word in words:
len_rval = len(' '.join(rval))
if len_rval + 1 + len(word) > max_chars :
break
rval.append(word)
return ' '.join(rval)
for i in ( 15, 16, 17,30,35):
cutdown = clean_cut( sample , i )
print "%s | %s" % ( i , cutdown )
and output is right…
15 | This is a
16 | This is a sample
17 | This is a sample
30 | This is a sample string and I
35 | This is a sample string and I would
The following implementation may work for you
Output
Note
Compared to textwrap, this implementation is 50 times faster