Python File Find String

Finding a string in a text file means checking its lines for the target. Python can print each matching line, and str.find() returns the first position of a substring in a string.

I’ll show how to scan a file line by line and what str.find() returns.

TL;DR

Use str.find(sub) when you need a substring’s first position. It returns -1 when the substring is absent.

  • Use needle in text for a True-or-False presence check.
  • Optional start and end arguments restrict the search like a slice, with end excluded.
  • To find text in a file, inspect each line and check it with in or find().

What Is Python String find()?

Python’s str.find() returns the lowest index where one string begins inside another, or -1 if no match exists.

Its form is text.find(sub[, start[, end]]). The optional range follows slice rules: start is included and end is excluded. Returned indices refer to the original text.

A match beginning at position 4 returns 4, even if the search starts at position 3.

Use in for a presence check, and compare find() with -1 when you need the position. Python’s str.find() reference documents both.

How to Find a String in a File Step by Step

Iterate over a text file to inspect matching lines as records.

Step 1: Search one string and read the returned index

I ran python3 find_demo.py against “banana” for a repeated match, a missing match and a bounded search. The output shows the first position, then -1 for both searches without a complete match.

text = "banana"
print(text.find("ana"))
print(text.find("xyz"))
print(text.find("ana", 2, 5))

Output from python3 find_demo.py:

1
-1
-1
Python str.find() returns the first match position or minus one

The first match begins at index 1, while the bounded call searches text[2:5], or “nan”, and returns -1 because that range lacks the complete substring “ana”.

Step 2: Scan a text file line by line

File iteration yields one line at a time, and enumerate() adds human-readable line numbers while in tests each line for the target.

For a known UTF-8 file, set encoding=”utf-8″ when opening it, and the with statement closes the file when its block ends, including after an error.

from pathlib import Path

path = Path("notes.txt")
path.write_text("Python strings are text.\nFind a string in this line.\n", encoding="utf-8")
needle = "string"
with path.open(encoding="utf-8") as file:
    for line_number, line in enumerate(file, start=1):
        if needle in line:
            print(f"{line_number}: {line.rstrip()}")

Run python3 file_search_demo.py. It creates notes.txt in the current directory, so change the path to protect an existing file. Output:

1: Python strings are text.
2: Find a string in this line.
Python file search prints matching lines with their line numbers

The loop prints complete matching records, rather than numeric character positions. For related tasks, see AskPython’s guides to reading a file as a string and reading and parsing text files.

Common Errors and Edge Cases

Guard missing results and choose how repeated matches should be handled.

SituationWhat happensChoice
Substring absentfind() returns -1Check the result before slicing
Only presence mattersin returns True or FalseUse needle in text
Missing match should raiseindex() raises ValueErrorUse index() inside suitable error handling
All matching file linesEach line is checked independentlyContinue scanning instead of stopping at the first result

Check for -1 before slicing. Since -1 is a valid negative boundary, text[:text.find(“!”)] silently turns “hello” into “hell” when the mark is absent.

find() returns the first occurrence. Search from a later position for another, advancing by one to include overlapping matches. Searches are case-sensitive.

An empty target matches the beginning of the searched range, so validate user input if that should not count. A decoding error can occur before the search.

Pass a known encoding, as described in Python’s open() documentation. Use index() if a missing match should raise ValueError.

Conclusion

Use find() for character positions and file iteration for matching records.

See AskPython’s file-as-string guide and the Python standard library reference.

FAQ

These answers cover the choices readers commonly make when locating text.

How do I find a string in a file in Python?

Open the text file and iterate over its lines. Test each line with needle in line or line.find(needle) != -1, then print or store matching lines.

What does str.find() return when the text is missing?

It returns -1 when the substring is absent from the searched range.

How do I find all occurrences of a substring?

Call find() repeatedly with a later start position after each match, or scan each file line and keep every matching line. Advance by one character when overlapping matches should count.

Vijaykrishna Ram
Vijaykrishna Ram
Articles: 99