Python 3 reference · String Methods
Python String find() Method
Return the lowest index where a substring is found, or -1 if it isn't. Optional start and end limit the search.
Python 3 Since 3.0
Syntax
str.find(sub, start=0, end=len(s))
Parameters
| Parameter | Description |
|---|---|
sub |
The substring to look for. |
start, end optional |
Only search this slice. |
Return value
The index (an int), or -1.
Examples
text = "hello world"
print(text.find("o"), text.find("o", 5), text.find("z"))
Output
4 7 -1
email = "[email protected]"
at = email.find("@")
print(email[:at], email[at + 1:])
Output
ada example.com
print("cat" in "concatenate") # use in for yes/no checks
Output
True
find() vs index()
find() returns -1 when nothing is found; index() raises ValueError. Be careful: -1 is also a valid
index (the last character), so always compare with == -1 before slicing.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
str.index()· Return the lowest index of a substring, like find(), but raise ValueError when it is not found.str.rfind()· Return the highest index where a substring is found, searching from the right, or -1 if it isn't found.str.count()· Return the number of non-overlapping occurrences of a substring, optionally only between start and end positions.str.partition()· Split the string at the first occurrence of a separator into a 3-tuple: the part before, the separator, and the part after.- Python Strings · tutorial