Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Finding Text in a String with a Custom Python Function

1 min read .
Finding Text in a String with a Custom Python Function

Python already provides several ways to search strings, but sometimes you want more than a yes/no result. For example, a search interface may need to return a snippet containing the matching keyword plus some surrounding context.

A Context-Aware Search Function

def find_text(text, keyword, context=100):
    index = text.find(keyword)
    if index == -1:
        return None

    start = max(index - context, 0)
    end = min(len(text), index + len(keyword) + context)
    return text[start:end]

The function:

  1. Uses str.find() to locate the first occurrence.
  2. Returns None when the keyword is absent.
  3. Calculates a safe start and end position.
  4. Returns a substring containing the requested context.

Example

text = (
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
    "Python makes text processing straightforward."
)

snippet = find_text(text, "Python", context=20)
print(snippet)

For simple Unicode-aware case-insensitive matching, casefold() is generally stronger than lower():

def find_text_case_insensitive(text, keyword, context=100):
    index = text.casefold().find(keyword.casefold())
    if index == -1:
        return None

    start = max(index - context, 0)
    end = min(len(text), index + len(keyword) + context)
    return text[start:end]

This works because case folding preserves string length for many common inputs, but not every Unicode transformation is guaranteed to map character positions perfectly. For advanced internationalized search, use a more deliberate normalization strategy.

Find Every Match

If you need multiple occurrences, repeatedly search from the end of the previous match:

def find_all(text, keyword):
    start = 0
    positions = []

    while True:
        index = text.find(keyword, start)
        if index == -1:
            return positions
        positions.append(index)
        start = index + len(keyword)

For overlapping matches or pattern-based searches, the re module may be more appropriate.

Built-in Alternatives

Use:

keyword in text

when you only need a Boolean.

Use:

text.find(keyword)

when you need an index without an exception.

Use:

text.index(keyword)

when a missing substring should raise ValueError.

Conclusion

A custom function is useful when your application needs a search result plus surrounding context. Build it on top of Python’s standard string methods, return a clear missing-value signal such as None, and use regular expressions only when the search requirements genuinely need pattern matching.

Related Posts

chevron-up