Skip to content

Module 7 · Strings — topic 15 of 22

find()

find() returns the index of the first occurrence of a substring, or -1 if it isn’t there. Learn start and end arguments, rfind(), index() and when the in operator is enough.

Beginner 10 min read·Lesson 96 of 306 in Python Programming

Learning objectives

  • Locate substrings with find() and rfind()
  • Handle the -1 not-found result
  • Choose between find(), index() and in

Definition

find() returns the index of the first occurrence of a substring, or -1 if it isn’t there. Learn start and end arguments, rfind(), index() and when the in operator is enough.

Introduction

find(sub) searches a string for a substring and returns the index where it first appears. If the substring isn’t present, it returns -1 instead of raising an error.

Why it matters

Knowing where text appears lets you extract what comes before or after it: the domain after @ in an email, the value after a colon, the extension after the last dot.

Detailed explanation

Searching text is one of the most common operations in programming, and Python offers a ladder of tools: in for yes/no questions, find() and index() for positions, count() for frequency, and regular expressions for patterns. Starting with the simplest tool that answers your question keeps code readable.

find() compares characters exactly, so it is case-sensitive. To search regardless of case, lower-case both the text and the substring first, then use the position on the original text if you need to extract the original characters.

find(sub) returns the lowest index where sub starts, or -1.

find(sub, start, end) searches only between start and end, which lets you find later occurrences.

rfind(sub) returns the highest index, searching from the right, useful for the last dot or slash.

index(sub) behaves like find() but raises ValueError when the substring is missing. Use it when absence is truly an error.

If you only need to know whether the substring exists, use in; it is clearer than find(...) != -1.

Be careful: -1 is also a valid negative index, so slicing with an unchecked find() result can silently produce wrong text. Always check for -1 first.

Syntax

Python
pos = text.find(sub)
if pos != -1:
after = text[pos + len(sub):]
last = text.rfind(sub)
  • find returns an index or -1.
  • Check for -1 before slicing.
  • rfind searches from the end.

Code examples

Finding positions

Python
email = "asha.rao@kenholt.info"
print(email.find("@"))
print(email.find("."))
print(email.rfind("."))
print(email.find("#"))
Output
8
4
16
-1

find versus index

Python
text = "hello"
print(text.find("z"))
try:
text.index("z")
except ValueError as err:
print("ValueError:", err)
Output
-1
ValueError: substring not found

More examples

Extracting parts safely

Python
def domain(email):
at = email.find("@")
if at == -1:
return None
return email[at + 1:]
for e in ["asha.rao@kenholt.info", "not-an-email"]:
print(e, "->", domain(e))
log = "ERROR at line 12; ERROR at line 40"
first = log.find("ERROR")
second = log.find("ERROR", first + 1)
print(first, second)
filename = "report.final.pdf"
print(filename[filename.rfind(".") + 1:])
Output
asha.rao@kenholt.info -> kenholt.info
not-an-email -> None
0 18
pdf

Step-by-step explanation

  • domain() checks for -1 before slicing so invalid input returns None.
  • email[at + 1:] takes everything after the @ sign.
  • The second find starts just after the first match to locate the next ERROR at index 18.
  • rfind(".") finds the last dot so the extension is pdf, not final.pdf.

Expected output

Running “Extracting parts safely” prints exactly:

TextOutput
asha.rao@kenholt.info -> kenholt.info
not-an-email -> None
0 18
pdf

Practical applications

  • Email and URL parsers find separators such as @ and ://.
  • Log analysers search for keywords and extract surrounding text.
  • File tools find the last dot to get extensions.

Best practices

  • Always handle the -1 case.
  • Use in for yes/no checks.
  • Use index() when absence should be an error.

Common mistakes

Slicing with an unchecked -1

Avoid

text[text.find(":") + 1:] # whole text if no colon

Prefer

pos = text.find(":")
value = text[pos + 1:] if pos != -1 else ""

-1 + 1 is 0, so a missing colon silently returns the whole string.

Using find just to test presence

Avoid

if text.find("@") != -1:

Prefer

if "@" in text:

in expresses a presence test directly.

Key takeaways

  • find returns the first index of a substring or -1.
  • rfind searches from the right; index raises ValueError.
  • Check for -1 before using the result.

Try it yourself

  1. 1
    Extract the username before @ in an email address using find().
  2. 2
    Find the position of the second space in a sentence.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic