【问题标题】:Getting an error of substring not found for below code [closed]获取以下代码未找到子字符串的错误[关闭]
【发布时间】: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

【问题讨论】:

    标签: python string


    【解决方案1】:

    您要求 Python 在空切片中查找 e;第二个和第三个参数是 startend 索引。 s2[50:0] 是一个空字符串:

    >>> s2 = "fast and furious series from one to seven"
    >>> s2[50:0]
    ''
    

    如果您想通过从末尾搜索来查找文本,请使用str.rindex() function

    >>> s2.rindex('e')
    39
    

    【讨论】:

    • 但是根据代码它将从右到左以相反的顺序搜索,我通过更改起始索引(如 s2.index('e', 40, 0))尝试了上述代码。我仍然遇到同样的错误
    • 如果我正在为 find() 方法编写类似的代码,那么它可以工作,但不能用于 index () 方法。请解释一下
    • @NikhilKadam:是什么让你认为它会反向搜索?根据什么代码?
    • 我通过教程学到的东西,find() 方法和 index() 方法都确定 str 是出现在字符串中还是出现在字符串的子字符串中。因此,为 find() 方法执行的代码显示的是结果,而不是 index() 方法。 print "s2.find('e', 10, 0) : ",s2.find('e', 10, 0)
    • @NikhilKadam: findindex 找到完全相同的东西,index 在没有找到任何东西时引发异常,find 返回 -1。没有其他区别。 end 参数小于或等于 start 意味着您搜索一个空字符串并且永远找不到任何东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 2020-10-19
    • 2017-01-11
    • 2022-08-18
    • 2016-08-03
    • 2014-11-20
    • 1970-01-01
    相关资源
    最近更新 更多