PythonPython StringsPython substring search
How do you find the position of a substring?
Question 73 of 88 · Updated
On this page
- 1. Find the first or last occurrence
- 2. Restrict the search with start and end
- 3. Empty substring and boundary cases
- 4. What is the difference between find() and index()?
- 5. Find every occurrence, including optional overlaps
- 6. Unicode code-point positions are not byte offsets
- 7. Practical example: extract a value after the first delimiter
- 8. Errors, performance and selection
- Interview-ready answer
- Official references
Use text.find(substring) to obtain the zero-based starting position of the first occurrence of a literal substring. It returns -1 when the substring is absent. Use index() instead if an absent substring should raise ValueError. For the last occurrence, use rfind() or rindex().
These methods search an immutable string without changing its contents. They locate matching Unicode code-point sequences, not byte offsets or regular-expression patterns.
1. Find the first or last occurrence#
PYTHONtext = 'banana' print(text.find('ana'), text.rfind('ana')) print(text.find('xyz'), text.find('ban'))
Output:
1 3
-1 0The substring ana starts at two positions in banana, namely 1 and 3. The matches overlap. The find method returns the lowest matching starting index; rfind returns the highest.
| Character | b | a | n | a | n | a |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
An index identifies the start of the match, not its end. If a nonempty substring of length m is found at position i, the matching interval is [i, i + m), with the upper bound excluded.
The result zero is a valid successful match at the first character. A negative result of -1 is the specific missing-value sentinel for find and rfind.
2. Restrict the search with start and end#
PYTHONtext = 'banana' print(text.find('ana', 2), text.find('ana', 0, 3)) print(text.find('ana', -4), text.rfind('ana', 0, 4))
Output:
3 -1
3 1The general signatures are find(sub[, start[, end]]) and rfind(sub[, start[, end]]). The same optional bounds are available for index and rindex.
The start bound is inclusive and the end bound is exclusive. A match must fit completely within the search interval. In the second call, the first occurrence of ana would extend beyond the exclusive boundary at index 3, so it is not selected.
Negative bounds are interpreted relative to the string length. The returned positions remain relative to the original string, not to the beginning of the selected interval.
For nonempty needles, the effect of valid integer bounds can generally be understood by considering the corresponding slice and translating its match position back into the original coordinates. Prefer passing bounds directly rather than constructing a temporary substring. This also avoids losing the original coordinate system.
Do not generalize slice equivalence blindly to empty needles or starts beyond the string's length, as the next section illustrates.
3. Empty substring and boundary cases#
PYTHONtext = 'abc' print(text.find(''), text.rfind('')) print(text.find('', 3), text.find('', 4)) print(text.find('', 2, 1))
Output:
0 3
3 -1
-1An empty substring matches at boundaries between code points, including the beginning and end. The first boundary is zero and the last boundary is len(text).
A search beginning exactly at len(text) can find an empty substring there. A start beyond len(text) does not find an empty substring. A reversed search interval also fails in the demonstrated case.
This distinction matters when implementing searches using slices. For example, text[4:] is an empty string, whose find('') returns zero; text.find('', 4) instead returns -1. Slicing may clamp a start to the sequence length while the search method retains the distinction for an empty needle.
An empty search value is legal Python, but an application may reject it when it has no useful interpretation. In particular, repeated-search algorithms must handle empty patterns explicitly to guarantee progress.
4. What is the difference between find() and index()?#
PYTHONtext = 'banana' print(text.index('ana'), text.rindex('ana')) try: text.index('xyz') except ValueError: print('missing substring')
Output:
1 3
missing substring| Method | Matching occurrence | If absent |
|---|---|---|
| find() | First | Returns -1 |
| rfind() | Last | Returns -1 |
| index() | First | Raises ValueError |
| rindex() | Last | Raises ValueError |
For an ordinary string, valid bounds and a matching substring, find and index return the same position. The corresponding right-search methods also agree. Their central distinction is how absence is represented.
Choose find when absence is an ordinary expected outcome and a sentinel is useful. Choose index when the caller requires the substring to exist and a missing value should be treated as an exception. Both methods can also raise other exceptions for invalid argument types.
If only existence matters, use the membership expression sub in text. There is no need to request a numeric position.
A common bug is writing if text.find(sub):. In Python, zero is falsey and -1 is truthy. This reverses the intended behavior at the beginning of the string and when the substring is absent. Compare the result explicitly with -1.
5. Find every occurrence, including optional overlaps#
PYTHONdef positions(text, needle, overlapping=False): if not needle: raise ValueError('empty needle') start = 0 while True: pos = text.find(needle, start) if pos == -1: return yield pos start = pos + (1 if overlapping else len(needle)) print(list(positions('banana', 'ana'))) print(list(positions('banana', 'ana', overlapping=True))) print(list(positions('abc', 'z')))
Output:
[1]
[1, 3]
[]The generator searches from an updated starting position after each successful match. Advancing by the needle length prevents overlap. Advancing by one allows a new match to begin inside the preceding matched interval.
The function assumes ordinary strings and a Boolean overlap policy. Since it is a generator function, validation occurs when iteration begins. It rejects an empty needle rather than defining a separate boundary-enumeration policy.
Using a generator avoids storing all match positions inside the function; wrapping it in list materializes them. If the caller needs only the number of non-overlapping matches, str.count() is a more direct operation. It does not count overlapping matches.
The helper is not a promise of optimal substring-search complexity for every workload. Repeated bounded searches can perform additional work, especially with long patterns and dense overlapping matches.
6. Unicode code-point positions are not byte offsets#
PYTHONtext = 'é🙂abc' print(text.find('a')) print(text.encode('utf-8').find(b'a'))
Output:
2
6The string contains two Unicode code points before a. In UTF-8, é occupies two bytes and the emoji occupies four bytes, so a begins at byte offset six.
Do not mix the two coordinate systems. A byte offset returned by a binary protocol cannot generally be used as a Python str index. A Python code-point index also does not necessarily identify a user-perceived grapheme-cluster boundary.
Search is literal and case-sensitive. Canonically equivalent Unicode sequences need not match without normalization. If a transformed string is searched, its positions belong to the transformed string, not necessarily the original. Unicode normalization and case folding can change lengths; recovering exact original offsets requires a deliberately designed mapping or search procedure.
For regular-expression patterns, re.search provides a match object with start(), end() and span() methods. It is not interchangeable with literal substring search. A later regular-expression lesson covers pattern semantics in detail.
7. Practical example: extract a value after the first delimiter#
PYTHONdef extract_value(line): pos = line.find('=') if pos == -1: return None return line[pos + 1:] print(repr(extract_value('name=Ada'))) print(repr(extract_value('=ready'))) print(repr(extract_value('key='))) print(repr(extract_value('missing')))
Output:
'Ada'
'ready'
''
NoneThe function distinguishes a missing delimiter from an existing delimiter with an empty value. It also correctly handles a delimiter at position zero.
The policy permits an empty key, since it extracts only the remainder. If the input format requires a nonempty key, perform that validation separately. This is not a complete configuration parser.
For simple delimiter-based extraction, partition() can sometimes express the intent more directly. For a known fixed literal boundary, find is useful when the actual offset is needed for slicing, reporting or further searches.
8. Errors, performance and selection#
| Expression | Expected result |
|---|---|
'abc'.index('z') | ValueError |
'abc'.rindex('z') | ValueError |
'abc'.find(b'a') | TypeError |
'abc'.find('a', 1.5) | TypeError |
These four error cases were tested independently. The needle must be a string for ordinary str searches. Bounds must be supported integer-like values. A missing literal substring is not itself a type error.
A naive search across n code points for a pattern of length m can require O(n*m) character comparisons. CPython uses optimized substring-search implementations and may choose different strategies depending on the operation and inputs. Do not claim that Python's language contract guarantees one particular search algorithm or a universal complexity bound across interpreters.
For a fixed nonempty needle of bounded length, a linear-in-input-size worst-case model is generally useful for ordinary searches. The returned index itself requires no large result allocation. Passing bounds avoids the need to construct a temporary sliced string. Repeated searches, normalization and pattern transformations have their own costs.
| Requirement | Recommended interface |
|---|---|
| Check literal presence only | in |
| Find first position, absence expected | find() |
| Find first position, absence exceptional | index() |
| Find last position | rfind() or rindex() |
| Count non-overlapping occurrences | count() |
| Check an exact prefix or suffix | startswith() or endswith() |
| Locate a pattern | re.search() |
For search-driven application logic, test first-position matches, absent needles, repeated matches, bounds that exclude a partial match, empty patterns and non-ASCII text.
Interview-ready answer#
Use str.find(sub, start, end) to locate the first occurrence of a literal substring. It returns the zero-based original string index or -1 if no match exists. The str.index method performs the same successful search but raises ValueError for absence. Their right-search counterparts return the last matching position. The start bound is inclusive, the end bound exclusive, and the full match must lie within the selected interval. Use in for membership alone and explicitly compare find's result with -1 rather than relying on its truthiness. Python str positions measure Unicode code points, not encoded byte offsets.
Official references#
- Python Standard Library — str.find
- Python Standard Library — str.index
- Python Standard Library — str.rfind
- Python Standard Library — str.rindex
- Python Standard Library — str.count
- Python Standard Library — re.search
- Python Unicode HOWTO
Verification note: Seven runnable example groups matched their expected outputs in independent namespaces on CPython 3.13.5. Four independent expected-exception tests passed. Across 500 seeded randomized strings, nonempty needles and valid nonnegative bounds, 1,000 assertions compared find and rfind against an independent exhaustive slice-based match enumeration. Empty-needle and negative-bound cases were covered by the deterministic examples. Three fenced Mermaid flowcharts were manually reviewed; the local Mermaid CLI was unavailable, so parser validation and public-site rendering were not performed. Official references are provided under the authorized offline research exception; live documentation and Supabase changelog were not checked.
References
- 1.Python Standard Library — str.finddocs.python.org
- 2.Python Standard Library — re.searchdocs.python.org
- 3.Python Unicode HOWTOdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design