Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python’s str.find() method returns the lowest (first) index where a substring occurs, or -1 when it is absent. Its syntax is string.find(sub[, start[, end]]). For example, "Python makes text processing easy".find("text") returns 19. Indexes are zero-based, and searching does not modify the original immutable string.

The official documentation recommends find() when you need the position; use the in operator when you only need a yes/no answer (Python documentation).

What find() does

find() searches a string for a literal substring and reports where the first complete match begins.

text = "Hello, Python!"
position = text.find("Python")
print(position)  # 7

It returns one index, not every match. Python strings are immutable, so the method only reads the string.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Syntax and search bounds

str.find(sub[, start[, end]])
  • sub: the substring to locate.
  • start: optional inclusive starting index.
  • end: optional exclusive ending index.

The optional bounds follow slice-style interpretation, equivalent in meaning to searching within text[start:end] without writing that slice explicitly.

text = "Python is widely used"
print(text.find("is"))          # 7
print(text.find("is", 8))       # -1
print(text.find("is", 0, 10))   # 7

Because end is exclusive, the complete match must fit before that boundary:

text = "abcdef"
print(text.find("cd", 0, 4))  # 2
print(text.find("cd", 0, 3))  # -1

Negative bounds use the same rules as slicing. They can be useful, but explicit nonnegative bounds are often clearer in beginner and maintenance code.

text = "Python programming"
print(text.find("Python", -10))  # 0
print(text.find("Python", 0, -1)) # 0
print(text.find("x", 100))       # -1

Basic results and the -1 sentinel

When a match exists

text = "apple banana apple"
print(text.find("apple"))  # 0

The result is the lowest matching index.

When no match exists

position = "Python".find("Java")
print(position)  # -1

-1 is a normal return value, not an exception. Check it explicitly:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
position = text.find("Java")
if position == -1:
    print("Substring not found")
else:
    print(f"Found at index {position}")

The index-zero truthiness trap

Do not use the result directly as a Boolean. Index 0 is falsey:

text = "Python"
if text.find("Python"):
    print("Found")  # does not run

Use position != -1, or use in when the index is unnecessary.

find() versus in

Need Preferred expression
First position text.find("Python")
Existence only "Python" in text
if "Python" in text:
    print("The text contains Python")

For strings, membership is defined as a substring test; the language reference notes the equivalent test text.find(sub) != -1 (membership-test documentation). Choose in for clearer intent when no location is needed.

find() versus index()

text = "Python"
print(text.find("Java"))   # -1
print(text.index("Java"))  # raises ValueError

index() has the same search parameters but raises ValueError if absent (index() documentation). Use it when missing text means invalid input or an exceptional state:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
try:
    position = text.index("required")
except ValueError:
    print("Required substring is missing")

Finding later, last, and multiple matches

Second and subsequent non-overlapping matches

text = "apple banana apple"
needle = "apple"
first = text.find(needle)
second = text.find(needle, first + len(needle))
print(first, second)  # 0 13

Using len(needle) avoids a hard-coded offset.

All matches

def find_all(text, needle):
    if needle == "":
        raise ValueError("needle must not be empty")
    positions = []
    start = 0
    while True:
        position = text.find(needle, start)
        if position == -1:
            return positions
        positions.append(position)
        start = position + len(needle)

print(find_all("red blue red green red", "red"))  # [0, 9, 19]

Advancing by len(needle) skips overlapping matches. Advance by one character when overlaps should count:

text = "aaaa"
needle = "aa"
positions = []
start = 0
while True:
    position = text.find(needle, start)
    if position == -1:
        break
    positions.append(position)
    start = position + 1
print(positions)  # [0, 1, 2]

Rightmost match with rfind()

rfind() returns the highest matching index (documentation).

path = "archive/2026/report.pdf"
dot = path.rfind(".")
if dot != -1:
    extension = path[dot + 1:]

For actual filesystem paths, prefer pathlib:

from pathlib import Path
extension = Path("report.final.csv").suffix

Case-insensitive and Unicode-aware searching

find() is case-sensitive:

"Python".find("Python")  # 0
"Python".find("python")  # -1

For simple ASCII data, normalize both values with lower(). For broader Unicode case handling, casefold() is generally preferable:

text = "Python Programming"
needle = "python"
position = text.casefold().find(needle.casefold())
print(position)  # 0

Case folding can change character relationships in some languages. If the returned index must refer precisely to the original string, test the target language data rather than assuming the normalized index maps directly. Unicode normalization may also matter: visually identical strings such as precomposed é and eu0301 can have different underlying representations.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Empty needles

An empty string is considered a substring. Its result is the beginning of the permitted range:

text = "Python"
print(text.find(""))       # 0
print(text.find("", 3))    # 3
print(text.find("", 3, 5)) # 3

Validate user-supplied search terms when an empty query is not meaningful:

needle = user_input.strip()
if not needle:
    print("Please enter a non-empty search term")

Literal text, words, and regular expressions

find() searches character sequences, not whole words and not patterns:

"concatenate".find("cat")  # 3
"cat".find("at")            # 1
"Order 123".find(r"d+")   # -1; searches literal backslash, d, and +

Use re.search() for character classes, alternatives, quantifiers, groups, or boundary rules:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
import re
match = re.search(r"d+", "Order 123")
if match:
    print(match.start())  # 6

Do not introduce a regular expression when a literal search expresses the requirement more clearly.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Strings, bytes, and compatible types

str.find() returns a string index, not a UTF-8 byte offset:

text = "café"
print(text.find("é"))

For encoded data, search bytes consistently:

data = "café".encode("utf-8")
print(data.find("é".encode("utf-8")))

Mixing text and bytes raises TypeError:

"abc".find(b"b")  # TypeError

Decode bytes before text processing, or keep both haystack and needle as bytes. Avoid blindly converting arbitrary values with str(); explicit type validation prevents hidden data-quality errors. Python documents separate methods for text and binary sequences (bytes and bytearray operations).

Practical patterns and better alternatives

Extracting text after a known marker

line = "Name: Ada Lovelace"
marker = "Name: "
position = line.find(marker)
if position != -1:
    name = line[position + len(marker):]

For a required prefix, a dedicated operation is clearer:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
if line.startswith("Name: "):
    name = line.removeprefix("Name: ")

Detecting a delimiter

header = "Content-Type: text/plain"
colon = header.find(":")
if colon != -1:
    key = header[:colon]
    value = header[colon + 1:].strip()

For one delimiter, split(":", 1) is often simpler. Use a parser for formats where delimiters may be quoted, escaped, nested, or malformed.

Searching a document section

document = "TITLEnINTRODUCTIONnBODYnCONCLUSION"
body_start = document.find("BODY")
conclusion_start = document.find("CONCLUSION")
if body_start != -1 and conclusion_start != -1:
    body = document[body_start:conclusion_start]

Do not use substring offsets as a substitute for an HTML, JSON, XML, CSV, URL, or other format-specific parser.

Choosing related methods

Requirement Tool Reason
Boolean membership in Communicates an existence test.
First index, absence is normal find() Returns an index or -1.
Missing text is an error index() Raises ValueError.
Rightmost index rfind() Searches from the right.
Prefix or suffix startswith() / endswith() Expresses the exact test.
Number of non-overlapping matches count() Returns a count, not positions.
Pattern matching re.search() Supports regular-expression syntax.
Filesystem path components pathlib Handles path semantics safely.

Common mistakes to avoid

  • Testing if text.find(...); index 0 is falsey.
  • Slicing with text[text.find("missing"):]; -1 unexpectedly starts at the last character.
  • Forgetting that matching is case-sensitive.
  • Using find() for a prefix or suffix instead of startswith() or endswith().
  • Advancing repeated searches by +1 when non-overlapping matches are required, or by +len(needle) when overlaps are required.
  • Allowing an empty user query unintentionally.
  • Mixing str and bytes.
  • Assuming substring search recognizes words, grammar, or structured data.

Quick decision guide

Use find() when you need the first literal substring position, optional bounds, and ordinary -1 handling. Use in for a Boolean answer, index() when absence should raise, rfind() for the last occurrence, dedicated prefix/suffix methods for boundary checks, regular expressions for patterns, and format-aware parsers for structured input. The current Python documentation for these behaviors is available at docs.python.org.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.