4

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
Linseykathleen
  • 43
  • 1
  • 1
  • 4

3 Answers3

7

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'
mathematical.coffee
  • 55,977
  • 11
  • 154
  • 194
2

There is no problem in using lists here. You can do something like

>>> st = "abc def ghi"
>>> words = st.split()
>>> words
['abc', 'def', 'ghi']
>>> if len(words)>2:
...     print " ".join(words[:2])
...
abc def

In the above case the word limit is 2 and I used List Slicing and str.join() to get the required output.

RanRag
  • 48,359
  • 38
  • 114
  • 167
1

Presuming the split() works as you intend, why not recombine the first 20 items into a string and return it?

warren
  • 32,620
  • 21
  • 85
  • 124