Python str.index() function
str.index()
Function in Python
The str.index()
function in Python is similar to str.find()
, as it is used to search for a specified substring within a string and return the index of its first occurrence. However, there is a key difference: if the substring is not found, str.index()
raises a ValueError
instead of returning -1
. This makes str.index()
useful when you expect the substring to be present and want to handle cases where it is not found with an exception.
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, causingstr.index()
to raise aValueError
, which is caught and printed.
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 index()
with overlapping substrings
Here:
- The substring
"ana"
is found starting at index1
.
Key Points:
str.index()
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 raises a
ValueError
. - 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) raises aValueError
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.