Find the Index of a Substring or Return a Default in Python

Finds the index of a substring using str.find() and returns a specified default value instead of -1 when the substring is not found.

Easy Python 3.9+ Aug 9, 2026 Strings & text 14 views 0 copies

Python code

9 lines
Python 3.9+
def find_substring_or_default(text, substring, default=-1):
    index = text.find(substring)
    return index if index != -1 else default

if __name__ == "__main__":
    text = "The quick brown fox jumps over the lazy dog"
    print(find_substring_or_default(text, "brown"))
    print(find_substring_or_default(text, "cat"))
    print(find_substring_or_default(text, "fox", default=100))

Output

stdout
10
-1
16

How it works

str.find(sub) returns the lowest index where sub is found, or -1 if it is not present. The ternary condition index if index != -1 else default swaps -1 for the caller's default value, making the fallback explicit. Because find returns -1 only for absence, checking != -1 is safer than truthiness since index 0 is valid. This wrapper keeps the standard library behavior while adding a clean way to handle missing substrings.

Common mistakes

  • Using `if index:` instead of `if index != -1:` — this treats index 0 as a miss.
  • Forgetting that `find` returns -1, not None, when the substring is absent.
  • Confusing `str.find` with `str.index`, which raises ValueError instead of returning -1.

Variations

  1. Use `text.index(sub)` inside a try/except to raise a custom error instead of a default.
  2. Use a regex `re.search(sub, text)` if pattern matching is needed.

Real-world use cases

  • Parsing log lines to find a keyword and falling back to a sentinel when the keyword is absent.
  • Looking up configuration keys in a text template and defaulting to a placeholder if not present.
  • Implementing a safe substring search in a CLI tool that reports "not found" instead of -1.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.