Python Word Length Function Example Needed
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 w
Solution 1:
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'
Solution 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']
>>>iflen(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.
Solution 3:
Presuming the split()
works as you intend, why not recombine the first 20 items into a string and return it?
Post a Comment for "Python Word Length Function Example Needed"