I learned about list comprehensions a few days ago, and now I think I’ve gone a little crazy with them, trying to make them solve all the problems. Perhaps I don’t truly understand them yet, or I just don’t know enough Python yet to make them both powerful and simple. This problem has occupied me for a while now, and I’d appreciate any input.
In Python, join a list of strings words into a single string excerpt that satisfies these conditions:
excerpt does not exceed integer maximum_lengthwords are not in excerpt, append an ellipsis character … to excerptwords appear in excerptwords = ('Your mother was a hamster and your ' +
'father smelled of elderberries!').split()
maximum_length = 29
excerpt = ' '.join(words) if len(' '.join(words)) <= maximum_length else \
' '.join(words[:max([n for n in range(0, len(words)) if \
len(' '.join(words[:n]) + '\u2026') <= \
maximum_length])]) + '\u2026'
print(excerpt) # Your mother was a hamster…
print(len(excerpt)) # 26
Yup, that works. Your mother was a hamster and fits in 29, but leaves no room for the ellipsis. But boy is it ugly. I can break it up a little:
words = ('Your mother was a hamster and your ' +
'father smelled of elderberries!').split()
maximum_length = 29
excerpt = ' '.join(words)
if len(excerpt) > maximum_length:
maximum_words = max([n for n in range(0, len(words)) if \
len(' '.join(words[:n]) + '\u2026') <= \
maximum_length])
excerpt = ' '.join(words[:maximum_words]) + '\u2026'
print(excerpt) # 'Your mother was a hamster…'
But now I’ve made a variable I’m never going to use again. Seems like a waste. And it hasn’t really made anything prettier or easier to understand.
Is there a nicer way to do this that I just haven’t seen yet?
see my comment about why "simple is better than complex"
that said, here's a suggestion
l = 'Your mother was a hamster and your father smelled of elderberries!'
last_space = l.rfind(' ', 0, 29)
suffix = ""
if last_space < 29:
suffix = "..."
print l[:last_space]+suffix
this is not 100% what you need, but rather easy to extend
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