Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 返回非-1索引的内容_Python_List - Fatal编程技术网

Python 返回非-1索引的内容

Python 返回非-1索引的内容,python,list,Python,List,嗨,我想知道如何让我下面的代码返回以下给定的输入 split_sentence("doghellomeyayahell") 返回 ["dog","hellomeyayahell",""] 而不是 ['dog', 'hellomeyayahel', 'l'] 我知道问题是,由于东西找不到'hello'字符串,它返回-1索引。如果可能的话,我该如何做才能使上述工作正常 def split_sentence(s): lst = [] first = s.find('hello

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

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
索引一起使用:

try:
    third = s.index('hello', first + 2)
except:
    third = len(s)

您不能让它返回其他内容,因此必须测试返回值

if third == -1:
    third = len(s)
thirds = s[third:]
您还可以将
try/except
索引一起使用:

try:
    third = s.index('hello', first + 2)
except:
    third = len(s)

为什么第二个字符串应该是“hellomeyayahell”?如果你真的在“hello”上分开,那么第二个字符串应该是“meyayahell”。第二个部分包括hello,这就是为什么它从第一个到第三个出现的原因。为什么第二个字符串应该是“hellomeyahell”?如果你真的在“hello”上分开,那么第二个字符串应该是“meyayahell”。第二部分包括hello,这就是为什么它从第一个到第三个看起来都一样