str.find()

Returns the index of the first occurrence of a fragment, or -1.

Returns
The index of the first occurrence, or -1.
Changes the original
No
On this page

Example

#
Python
email = "emma.smith@codeworlds.com"

at = email.find("@")
print(at)
print(email[:at])
print(email.find("#"))
print("codeworlds" in email)
Resultsaved result, you can check it
10
emma.smith
-1
True

Definition and usage

#

The find() method looks for a fragment in a string and returns the index of its first occurrence. If the fragment is not there, it returns -1 instead of raising an error.

The optional start and end arguments limit the search range. rfind() searches from the end and returns the index of the last occurrence.

To simply check whether a fragment is present, the in operator is clearer. The index() method works like find(), but raises ValueError when the fragment is missing.

Syntax

#
Syntax
string.find(sub, start=0, end=len(string))

Parameters

#
  • sub

    str

    The fragment to search for.
  • start

    int, optional

    The index to start searching from.
  • end

    int, optional

    The index to stop searching at (exclusive).

Good practices

#
  • Use in to check whether a fragment is present. Save find() for situations where you need the position.
  • Remember that -1 is a valid index in slices. Always check the result before using it to slice a string.

Related entries

#

Spotted a mistake or missing an example? Write to us.