str.find()
Returns the position where a piece of text first appears in a string, or -1 when it is not there at all.
str.find(sub[, start[, end]])find() searches a string for a smaller piece of text and tells you where it starts. Positions count from 0, so a match at the very beginning gives 0.
When the text is not there, find() returns -1 instead of raising an error. Its twin str.index() does the same search but raises ValueError when nothing is found.
If you only want to know whether the text is there, "@" in email is clearer than find(). Be careful with -1: used as a position it means "the last character", so a missed check can silently cut the wrong slice.
Parameters
| Parameter | What it is |
|---|---|
subrequired | The text to look for. |
startoptional, default 0 | Where to begin searching (a position, as in slicing). |
endoptional, default len(str) | Where to stop searching. The match must fit before this position. |
Return value
The position (an int) of the first match, or -1 if there is none.
Examples
1Find a word
text = "hello world"
print(text.find("world"))
print(text.find("o"))
print(text.find("python"))6 4 -1
2Cut a string at the position you found
email = "lena@mail.example"
at = email.find("@")
if at != -1:
print("User:", email[:at])
print("Domain:", email[at + 1:])User: lena Domain: mail.example
3Find every match with start
Start each new search one place after the last match.
text = "banana"
pos = text.find("a")
while pos != -1:
print(pos)
pos = text.find("a", pos + 1)1 3 5
4Search from the right with rfind()
path = "photos/2026/beach.jpg"
print(path.find("/"))
print(path.rfind("/"))
print(path[path.rfind("/") + 1:])6 11 beach.jpg
rfind() works like find() but gives the position of the last match.
Common mistakes
Using find() as a yes/no test
A match at position 0 gives 0, which counts as false, and a miss gives -1, which counts as true. That is the opposite of what you want. Use in.
word = "apple"
if word.find("a"):
print("found with find()")
else:
print("not found?!")
if "a" in word:
print("found with in")not found?! found with in
Slicing with -1 by accident
When the text is missing, -1 used as a slice position points at the last character, so you get a wrong result instead of an error. Always check for -1 first.
text = "no at sign"
pos = text.find("@")
print(repr(text[pos:]))'n'
Questions people ask
What is the difference between find() and index()?
They search the same way. When nothing is found, find() returns -1 and str.index() raises ValueError.
How do I check if a string contains a word?
Use in: "cat" in text gives True or False.
How do I find all positions of a substring?
Loop with find(sub, pos + 1) as in the example, or use [m.start() for m in re.finditer(sub, text)].
Is find() case-sensitive?
Yes. Search in text.lower() with a lower-case sub to ignore case.