按字数拆分字符串

2024-05-17 09:02:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,我想把它分成一个列表,这样列表中的每个元素都有N个单词。 如果最后一个元素没有足够的单词,请保持原样

例如:

>>> 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."]

我试着这样做:

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

但我不知道如何处理其他因素


Tags: 元素列表cutestringbyit单词very
2条回答

试试这个:

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))
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.']

相关问题 更多 >