Python Glossary Русский

all Python 3Byte sequencesfunction

bytes.find

bytes — search

Return the index of the first occurrence, or -1.

Syntax

b.find(...)

A miss comes back as -1 rather than an exception, which trips people up in conditions: -1 is truthy while a perfectly valid index of 0 is falsy, so always compare the result to -1 explicitly. If you only need to know whether the subsequence is there, the in operator reads better; reach for find when you will slice at the returned position.

Examples

print(b'banana'.find(b'na'))   # → 2
print(b'banana'.find(b'na', 3))   # → 4
print(b'name=Ann'.find(b'='))   # → 4
code = ord('n')
print(b'banana'.find(code))   # → 2
print(b'banana'.find(b'z'))   # → -1

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy