Python gets x first words per line

I am looking for code that takes 4 (or 5) first words in a script. I tried this:

import re my_string = "the cat and this dog are in the garden" a = my_string.split(' ', 1)[0] b = my_string.split(' ', 1)[1] 

But I can not take more than two lines:

 a = the b = cat and this dog are in the garden 

I would like to:

 a = the b = cat c = and d = this ... 
+7
python string
source share
3 answers

The second argument to the split() method is the limit. Do not use it and you will get all the words. Use it like this:

 my_string = "the cat and this dog are in the garden" splitted = my_string.split() first = splitted[0] second = splitted[1] ... 

Also, don't call split() every time you need a word, it's expensive. Do it once and then just use the results later, as in my example.
As you can see, there is no need to add a separator ' ' , since the default separator for the split() ( None ) function matches all spaces. You can use it, however, if you do not want to split into Tab , for example.

+15
source share

You can use fragment notation in the list created by split:

 my_string.split()[:4] # first 4 words my_string.split()[:5] # first 5 words 

NB are examples of commands. You must use one or the other, not both in a row.

+7
source share

You can easily break the line into spaces, but if your line does not have enough words, the assignment will fail if the list is empty.

 a, b, c, d, e = my_string.split()[:5] # May fail 

You’d better keep the list, rather than give each member an individual name.

 words = my_string.split() at_most_five_words = words[:5] # terrible variable name 

This is a terrible variable name, but I used it to illustrate the fact that you are not guaranteed to get five words - you are guaranteed only five words.

+6
source share

All Articles