代码之家  ›  专栏  ›  技术社区  ›  CoderCookie10

Python中string.find('hello')和string.index('hello')之间的区别

  •  0
  • CoderCookie10  · 技术社区  · 3 年前

    我在Python IDE中尝试了以下功能:

    >>> string = 'yeah, but no, but yeah, but no, but yeah'
    >>> string.find('yeah')
    0
    >>> string.index('yeah')
    0
    >>> string.find('no')
    10
    >>> string.index('no')
    10
    

    string.index() string.find() 看起来完全相同的函数,但名称不同!

    1 回复  |  直到 3 年前
        1
  •  1
  •   fuzzy drawings    3 年前

    不同之处在于函数如何处理未找到的子序列。 find() 会回来的 -1 而指数将上升 ValueError .

    find()

    返回找到子序列sub的数据中的最低索引,以便sub包含在片中 s[start:end] . 可选参数start和end解释为切片表示法。返回 -1

    index()

    查找() ,但提高 值错误 当找不到子序列时。