-1

I have a string, I want to split it into a list so that every element of the list has N words. If the last element does not have enough words, leave it as it is.

for example:

>>> Split_by_N_words(string="I grow a turtle. It's a very slow but cute animal.", N=4)
["I grow a turtle.", "It's a very slow", "but cute animal."]

I tried to do this:

def Split_by_N_words(string, N):
    word_list = [""]
    for a in string.split()[:N]:
        word_list[0] += a + " "
    .....

But I have no idea how to proceed with the other elements

AMC
  • 2,642
  • 7
  • 13
  • 35
Deftera
  • 98
  • 1
  • 6
  • 1
    Take a look at a similar question which deals with list https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks – Egor Laufer May 02 '20 at 20:57
  • 1
    Unless there is a good reason not to do so, variable and function names should follow the `lower_case_with_underscores` style. – AMC May 03 '20 at 01:07

2 Answers2

0

Try this:

def Split_by_N_words(string, N):
    word_list = string.split()
    out_list = []
    for el in range(0, len(word_list), N):
        out_list.append((" ".join(word_list[el:el+N])))
    return (out_list)

print (Split_by_N_words("I grow a turtle. It's a very slow but cute animal.", 4))
Hayden Eastwood
  • 928
  • 2
  • 10
  • 20
  • https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks – AMC May 03 '20 at 01:08
0
split(): splits the string at spaces
ls[i:i+4]: creates a list with 4 strings
" ".join(): concatenates the strings with spaces

In : ls= s.split()                                                                                                        

In : [ " ".join(ls[i:i+4]) for i in range(0,len(ls),4) ]                                                                  
Out: ['I grow a turtle.', "It's a very slow", 'but cute animal.']
kantal
  • 2,331
  • 2
  • 8
  • 15
  • https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks – AMC May 03 '20 at 01:08