[英](Python) __new__ method returning something other than class instance
[英]Returning something other than -1 index
嗨,我想知道如何在下面的代码中输入以下内容
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
您不能使其返回其他值,因此必须测试返回值。
if third == -1:
third = len(s)
thirds = s[third:]
您也可以将try/except
与index
:
try:
third = s.index('hello', first + 2)
except:
third = len(s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.