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.
Python code
9 linesdef 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
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
- Use `text.index(sub)` inside a try/except to raise a custom error instead of a default.
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.