Reference library

Strings & text

Format, split, join, parse, and clean text — everyday Python string patterns.

1 match
Strings & text easy

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.

substring string-index str-find
Python
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, "c…
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Strings & text — Python code examples

What you will find here

This page collects strings & text snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.