Python find() and index(): Find Substring Position (Examples)
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
Python provides two built-in string methods for locating a substring: find() and index(). Both accept the same inputs: the source string, the substring to search for, and optional start and end bounds that limit the search range. They return the zero-based index of the first occurrence.
The key difference is failure behavior. find() returns -1 when the substring is missing, making it convenient for conditional checks. index() raises a ValueError instead, so use it when a missing substring should be treated as an error. To locate later occurrences, pass a start position such as first_position + 1, or use rfind()/rindex() for the last occurrence.
The example code demonstrates first and second matches, missing substrings, exception handling, and bounded searches. Inputs are ordinary Python strings; outputs are integers or a caught exception. The search cost depends on the text length n and substring length m. A naive search is O(n*m) worst-case, while CPython uses optimized algorithms that are often closer to linear in practice. index() has the same search cost as find(), plus exception handling overhead when no match exists. Use find() for safe checks and index() when absence is unexpected.