Python find substring
last modified November 19, 2026 Python 3.15
In this article we show how to find substrings in Python strings.
A substring is a contiguous part of a string. Python offers several tools for searching, depending on the question we ask:
- the
inoperator: does the string contain the substring? findandindex: where is the first occurrence?rfindandrindex: where is the last occurrence?count: how many times does it occur?startswithandendswith: does the string begin or end with it?
All of them are case-sensitive. For patterns rather than fixed text we use regular expressions.
The in operator
The in operator returns True if the substring
occurs in the string.
text = 'An old silent pond, a frog jumps into the pond'
print('frog' in text)
print('toad' in text)
print('Pond' in text)
print('toad' not in text)
The search is case-sensitive, so Pond is not found. The
not in operator negates the test. This is the most readable way
to check for a substring when we do not need its position.
$ python in_operator.py True False False True
The find method
The find method returns the index of the first occurrence, or
-1 if the substring is not found.
text = 'An old silent pond, a frog jumps into the pond'
print(text.find('pond'))
print(text.find('frog'))
print(text.find('toad'))
pos = text.find('frog')
print(text[pos:pos + len('frog')])
Indexes start at zero. With the position and the length of the substring we can slice the match out of the text.
$ python find_method.py 14 22 -1 frog
The index method
The index method works like find, but raises a
ValueError when the substring is missing.
text = 'An old silent pond, a frog jumps into the pond'
print(text.index('frog'))
try:
print(text.index('toad'))
except ValueError as e:
print(f'error: {e}')
We use index when a missing substring is an error in the
program, and find when it is an expected case.
$ python index_method.py 22 error: substring not found
find is not a boolean
A frequent bug is to use the result of find directly in an
if statement.
text = 'pond in the garden'
if text.find('pond'):
print('found with find')
else:
print('not found with find')
if 'pond' in text:
print('found with in')
The substring is at index 0, which is false in a boolean context, while the
-1 of a failed search is true. The test is therefore wrong in both directions.
We compare the result with -1, or use in.
$ python find_falsy.py not found with find found with in
Searching a range
The find, index, and count methods
accept optional start and end arguments. They work
like slice indexes.
text = 'An old silent pond, a frog jumps into the pond'
print(text.find('pond'))
print(text.find('pond', 15))
print(text.find('pond', 15, 40))
print(text.find('s', 4, 10))
print('pond' in text[15:40])
Starting at index 15 skips the first pond at 14 and finds the
second one at 42. Limiting the end to 40 cuts it off. The returned index is
always relative to the whole string, not to the searched range. The slice in
the last line gives the same answer as the range, but it creates a copy of
that part of the string.
$ python start_end.py 14 42 -1 7 False
The last occurrence
The rfind and rindex methods search from the right
and return the index of the last occurrence.
files = ['photo.jpg', 'archive.tar.gz', 'README', '.bashrc']
for name in files:
pos = name.rfind('.')
ext = name[pos + 1:] if pos > 0 else ''
print(f'{name:15} rfind={pos:2} extension={ext!r}')
We take the file extension after the last dot. A dot at index 0 marks a
hidden file on Unix, not an extension, so we require a positive index. For
real paths, pathlib.Path.suffix does this work.
$ python rfind.py photo.jpg rfind= 5 extension='jpg' archive.tar.gz rfind=11 extension='gz' README rfind=-1 extension='' .bashrc rfind= 0 extension=''
All occurrences
To find every occurrence, we call find in a loop and start each
new search after the previous match.
def find_all(text, sub):
positions = []
pos = text.find(sub)
while pos != -1:
positions.append(pos)
pos = text.find(sub, pos + len(sub))
return positions
text = 'An old silent pond, a frog jumps into the pond'
print(find_all(text, 'pond'))
print(find_all(text, 'o'))
print(find_all('aaaa', 'aa'))
The loop ends when find returns -1. Continuing at
pos + len(sub) gives non-overlapping matches, so
aa is found twice in aaaa.
$ python find_all.py [14, 42] [3, 15, 24, 36, 43] [0, 2]
Overlapping matches
The string methods and re.finditer count only non-overlapping
matches. Overlapping matches need another approach.
import re
text = 'aaaa'
print(text.count('aa'))
positions = [i for i in range(len(text)) if text.startswith('aa', i)]
print(positions)
print([m.start() for m in re.finditer('aa', text)])
print([m.start() for m in re.finditer('(?=aa)', text)])
The startswith method with a position argument tests every
index. In the regular expression, the lookahead (?=aa) matches an
empty string followed by aa; because the match is empty, the
search moves forward by one character and finds the overlapping positions.
$ python overlapping.py 2 [0, 1, 2] [0, 2] [0, 1, 2]
Counting substrings
The count method returns the number of non-overlapping
occurrences.
text = '''An old silent pond
A frog jumps into the pond
Splash! Silence again.'''
print(text.count('pond'))
print(text.count('o'))
print(text.count('\n') + 1)
print(text.count('pond', 0, 20))
print(text.count(''))
print(len(text))
Counting newlines gives the number of lines minus one. The range arguments limit the count to the first 20 characters. The empty string is found before every character and at the end, so its count is the length plus one.
$ python count_method.py 2 5 3 1 69 68
startswith and endswith
The startswith and endswith methods check the
beginning or the end of a string. Both accept a tuple of alternatives.
urls = [
'https://example.com',
'http://example.org',
'ftp://files.example.net',
'example.com',
]
for url in urls:
secure = url.startswith('https://')
web = url.startswith(('http://', 'https://'))
print(f'{url:25} secure={secure!s:5} web={web}')
images = ['logo.PNG', 'photo.jpg', 'notes.txt']
print([f for f in images if f.lower().endswith(('.png', '.jpg'))])
With a tuple, the method returns True if any of the prefixes
matches. The argument must be a tuple; a list raises a
TypeError. We lowercase the file names before checking the
extensions, so logo.PNG matches too.
$ python starts_ends.py https://example.com secure=True web=True http://example.org secure=False web=True ftp://files.example.net secure=False web=False example.com secure=False web=False ['logo.PNG', 'photo.jpg']
Case-insensitive search
To ignore case, we convert both strings to the same case before searching.
The casefold method is meant for this purpose.
text = 'Die Hauptstraße ist lang'
query = 'STRASSE'
print(query in text)
print(query.lower() in text.lower())
print(query.casefold() in text.casefold())
print('ß'.lower(), 'ß'.casefold())
The German letter ß has no uppercase form of its own and is
written as SS in capitals. The lower method keeps
ß, so the search fails. The casefold method turns it
into ss and the search succeeds.
$ python ignore_case.py False False True ß ss
Whole words
A plain substring search also matches inside longer words. Regular expressions with word boundaries find whole words only.
import re
text = 'Cat food: concatenate the cat and the category'
print(text.count('cat'))
print(text.lower().count('cat'))
matches = re.finditer(r'\bcat\b', text, re.IGNORECASE)
print([m.start() for m in matches])
print(re.search(r'\bdog\b', text))
The count method finds cat inside
concatenate and category, and after lowercasing in
Cat too. The \b anchor matches the boundary between a
word character and a non-word character; with re.IGNORECASE we
get the two standalone words. The re.search function returns
None when there is no match.
$ python whole_words.py 3 4 [0, 26] None
Searching a list of strings
With a list, the in operator compares whole items, not
substrings. To search inside the items, we combine in with a
generator expression.
names = ['report_2024.csv', 'summary.txt', 'report_2025.csv', 'notes.md']
print('summary.txt' in names)
print('summary' in names)
print(any('summary' in name for name in names))
print([name for name in names if 'report' in name])
print(next((name for name in names if name.endswith('.md')), None))
print(next((name for name in names if name.endswith('.pdf')), None))
The second test is false, because no item is equal to
summary. The any function checks whether some item
contains the word. The list comprehension returns all matching items and
next the first one; its second argument is the default returned
when nothing matches.
$ python in_list.py True False True ['report_2024.csv', 'report_2025.csv'] notes.md None
Searching a file
In the last example we write a small case-insensitive search tool. It searches the following file.
An old silent pond A frog jumps into the pond Splash! Silence again. Over the wintry forest, winds howl in rage with no leaves to blow.
The program prints the file name, line number, and column of each match, and puts the match in brackets.
import sys
from pathlib import Path
def search(path, query):
needle = query.casefold()
hits = 0
with Path(path).open(encoding='utf-8') as f:
for lineno, line in enumerate(f, start=1):
line = line.rstrip('\n')
col = line.casefold().find(needle)
while col != -1:
end = col + len(needle)
marked = f'{line[:col]}[{line[col:end]}]{line[end:]}'
print(f'{path}:{lineno}:{col + 1}: {marked}')
hits += 1
col = line.casefold().find(needle, end)
return hits
query = sys.argv[1] if len(sys.argv) > 1 else 'in'
count = search('haiku.txt', query)
print(f'{count} matches for {query!r}')
For each line we search the casefolded line in a loop, as in the all
occurrences example. The column is 1-based, as in compilers and
grep. The positions are taken from the casefolded line and used
to slice the original one; this is correct as long as casefolding does not
change the length of the text, which is true for ASCII but not for words like
Straße. The query comes from the command line; without an argument
the program searches for in.
$ python search_file.py haiku.txt:2:14: A frog jumps [in]to the pond haiku.txt:3:20: Splash! Silence aga[in]. haiku.txt:5:11: Over the w[in]try haiku.txt:6:10: forest, w[in]ds howl in rage haiku.txt:6:20: forest, winds howl [in] rage 5 matches for 'in'
Source
str.find – Python documentation
Common sequence operations – Python documentation
In this article we have searched for substrings in Python. See also Python string slicing, Python replace string, Python re.finditer, and Python compare strings.
Author
List all Python tutorials.