您好我想知道如何在下面给出输入
时返回以下代码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
答案 0 :(得分:0)
你不能让它返回别的东西,所以你必须测试返回值。
if third == -1:
third = len(s)
thirds = s[third:]
您还可以将try/except
与index
:
try:
third = s.index('hello', first + 2)
except:
third = len(s)