返回除1索引以外的内容

2024-09-28 01:26:52 发布

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

嗨,我想知道如何让我下面的代码返回以下给定的输入

split_sentence("doghellomeyayahell")

返回

["dog","hellomeyayahell",""] 

而不是

['dog', 'hellomeyayahel', 'l'] 

我知道问题是,因为东西找不到'hello'字符串,所以它返回-1索引。如果可能的话,我该如何做才能使上述工作正常

def split_sentence(s):
    lst = []
    first = s.find('hello')
    firsts = s[0:first]
    third = s.find('hello', first +2, len(s))
    thirds = s[third:len(s)]
    second = s[first:third]
    lst.append(firsts)
    lst.append(second)
    lst.append(thirds)
    return lst

Tags: 代码hellolenfindsentencefirstsplitsecond

热门问题