嗨,我想知道如何让我下面的代码返回以下给定的输入
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
您不能让它返回其他内容,因此必须测试返回值
您还可以将
try/except
与index
一起使用:相关问题 更多 >
编程相关推荐