Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python word length function example needed

Tags:

python

string

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
like image 486
Linseykathleen Avatar asked Dec 28 '22 06:12

Linseykathleen


1 Answers

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'
like image 83
mathematical.coffee Avatar answered Dec 30 '22 10:12

mathematical.coffee