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,这就是为什么它从第一个到第三个看起来都一样