【发布时间】:2015-08-16 01:23:48
【问题描述】:
s2 = "fast and furious series from one to seven"
print "s2.index('e', 50, 0) : ", s2.index('e', 50, 0)
错误:
print "s2.index('e', 50, 0) : ", s2.index('e', 50, 0)
ValueError: substring not found
【问题讨论】:
s2 = "fast and furious series from one to seven"
print "s2.index('e', 50, 0) : ", s2.index('e', 50, 0)
错误:
print "s2.index('e', 50, 0) : ", s2.index('e', 50, 0)
ValueError: substring not found
【问题讨论】:
您要求 Python 在空切片中查找 e;第二个和第三个参数是 start 和 end 索引。 s2[50:0] 是一个空字符串:
>>> s2 = "fast and furious series from one to seven"
>>> s2[50:0]
''
如果您想通过从末尾搜索来查找文本,请使用str.rindex() function:
>>> s2.rindex('e')
39
【讨论】:
find 和 index 找到完全相同的东西,index 在没有找到任何东西时引发异常,find 返回 -1。没有其他区别。 end 参数小于或等于 start 意味着您搜索一个空字符串并且永远找不到任何东西。