What find() does
A string is a sequence of characters, and each character has a position, called an index, counted from 0. The find() method searches a string for a smaller piece of text, called a substring, and tells you where it starts. It is the tool to reach for when you need the position of something inside a string, for example to cut the string at that point.
sentence = "Hello World"
print(sentence.find("World")) # 6
print(sentence.find("xyz")) # -1
The result is the index of the first character of the match. In "Hello World" the letters H e l l o take indices 0 to 4, the space is at 5, and the W of "World" is at 6. When the substring does not occur, find() returns -1, which can never be a real position.
The related methods and arguments
Searching from a later position
A second argument tells find() where to start looking. The index it returns still counts from the beginning of the whole string:
s = "Hello World"
print(s.find("o")) # 4
print(s.find("o", 5)) # 7
print(s.find("o", 8)) # -1
The first "o" is at index 4. Starting at index 5 skips it and finds the one inside "World" at index 7. Starting at index 8 leaves no "o" to find.
find() versus index()
The index() method works the same way but reacts to a missing substring differently. Instead of returning -1 it raises an error:
s = "Hello World"
try:
s.index("xyz")
except ValueError as e:
print("ValueError:", e)
ValueError: substring not found
Use find() when "not found" is a normal outcome you want to handle with an if. Use index() when a missing substring would be a bug and you want the program to stop loudly.
Other useful relatives
rfind()searches from the right, so it returns the position of the last occurrence:"Hello World".rfind("o")is7.count()returns how many times a substring occurs:"Hello World".count("o")is2.- The
inoperator answers a plain yes or no:"World" in "Hello World"isTrue. If you do not need the position,inis the simpler choice.
Gotchas
- Case matters.
"Hello World".find("world")returns-1, because lowercasewis a different character fromW. Lower both strings first if you want a case-insensitive search. - Only the first match is reported.
find()returns one index. To locate the next occurrence, search again with a start argument just after the previous match. - Do not use the result as a condition. Writing
if s.find("H"):looks reasonable, but the match is at index0, and0counts as false, while the not-found value-1counts as true. Compare explicitly:if s.find("H") != -1:, or usein. - The empty string is always found.
s.find("")returns0. - Negative results are not indices. A returned
-1must be checked before you use it to slice or index. Python would acceptsentence[-1], but it would give you the last character, not an error.
The exercise, step by step
The lesson gives you a variable sentence containing "Hello World" and asks for the index where "World" begins.
- Pick the method. You want a position, and the lesson expects the value
-1rather than an error if the text were missing, so the method isfind. - Call it on
sentence. Writesentence.find("World"), passing the text to search for as a string. - Store the answer in
idx. Assign the call to a new variable of that name, below the existing line.
sentence = "Hello World"
idx = sentence.find("World")
The variable idx now holds 6. You can check that it points at the right place by using it to index the string or to slice it:
print(idx) # 6
print(sentence[idx]) # W
print(sentence[idx:]) # World
Key takeaways
s.find(sub)returns the index of the first occurrence ofsub, or-1when it is absent.s.find(sub, start)begins searching atstart, and the result is still an index into the whole string.s.index(sub)behaves the same, but raisesValueErrorwhen the substring is missing.- Searches are case sensitive.
- Compare the result with
-1instead of treating it as true or false.