I'm having a little bit of trouble with my homework. I was supposed to write a function "limitWords" that restricts input to twenty words and truncates the input down to only 20 words if it's more than 20 words.
I used "len(text.split())" as a means to count up the words, so the 20 or less part works, but I don't know how to truncate the input without changing it into a twenty word list.
I don't know if the way I did the first part of my if statement properly, but input on the second bit would be helpful. I'm not looking for a copy and paste answer -- explanation or an example that's similar would be preferred. Thanks!
totalwords = len(text.split())
if totalwords <= 20:
return text
I think the list approach is quite viable -- you're almost there already.
Your text.split()
already produces an array of words, so you can do:
words = text.split()
totalwords = len(words)
Then, you could select the first 20 as you say (if there's too many words), and join the array back together.
To join, look at str.join.
As an example:
'||'.join(['eggs','and','ham'])
# returns 'eggs||and||ham'
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