Python str.find() function
str.find()
Function in Python
The str.find()
function in Python is used to search for a specified substring within a string and return the index (position) of its first occurrence. If the substring is not found, it returns -1
. This function is useful for checking the presence of a substring in a string and determining its position.
Syntax:
substring
: The substring you want to search for.start
(optional): The starting index from where the search should begin. The default is0
.end
(optional): The ending index where the search should stop. The default is the end of the string.
Example 1: Basic usage
In this example:
- The substring
"world"
is found at index7
in the string"Hello, world!"
.
Example 2: Substring not found
Here:
- The substring
"Python"
is not found in the original string, so the result is-1
.
Example 3: Specifying start and end indices
In this case:
- The search for
"world"
starts from index10
, and the first occurrence of"world"
after that is found at index27
.
Example 4: Using find()
with overlapping substrings
Here:
- The substring
"ana"
is found starting at index1
.
Key Points:
str.find()
returns the index of the first occurrence of the specified substring.- It is case-sensitive, meaning
"Hello"
and"hello"
are considered different. - If the substring is not found, it returns
-1
. - You can specify optional
start
andend
parameters to limit the search range within the string. - The function does not modify the original string.
Example 5: Case sensitivity
In this example:
- The search for
"hello"
(lowercase) returns-1
because it is not found in the original string.
Example 6: Multiple occurrences
Here:
- The first occurrence of
"apple"
is found at index0
, even though there is a second occurrence later in the string.