Solved

find() vs index() — which one?

HenryWritesOP

Both return the position. What's the point of having two?

0

Comments 4

Join the discussion

Already have an account? Log in

  1. Grace_42 Solutionreplies: 2

    The difference is what happens when the text isn't there:
    - find() returns -1
    - index() raises ValueError

    Use find() when "not found" is normal, index() when it should never happen and you want to know loudly.

    6
      1. FreyaL

        Oof, I have exactly that bug somewhere. Off to fix it.

        1
    1. LucasVD

      Careful with find() in conditions: if s.find("x"): is wrong, because position 0 is falsy and -1 is truthy! Use if "x" in s: for simple checks.

      6