Python String index() Method
str.index(sub) returns the position of the first occurrence of sub in a string, and raises ValueError if sub is not found.Use index() when you are sure the text you are looking for is there and a missing value would be a bug. It works exactly like find(), except for what happens on a miss: find() quietly returns -1, while index() stops with an error. Positions start at 0, as with every Python string.
| Syntax | text.index(sub, start, end) |
|---|---|
| Parameters | sub: the substring to look for; start and end (optional): search only inside text[start:end] |
| Returns | The lowest index where sub begins (an int) |
| If not found | Raises ValueError: substring not found |
| Case sensitive | Yes: "Python".index("p") fails |
How str.index() searches a string
Python scans from left to right and returns the index of the first character of the first match. The match may be one character or many.
word = "banana"
print(word.index("b"))
print(word.index("na"))
print(word.index("a"))The last call returns 1, not 3 or 5, because only the first match counts. Because a string is a sequence, the number you get can be used directly in slicing, as shown in the examples below.
Using the start and end arguments
The optional start and end arguments limit the search to text[start:end]. The returned index is still counted from the beginning of the whole string, not from start. This is the usual way to find the second occurrence: search once, then search again from just after the first hit.
path = "a/b/c"
first = path.index("/")
second = path.index("/", first + 1)
print(first, second)index() vs find() vs rindex()
Pick the method by what you want to happen when the text is missing.
| Method | Searches from | If not found | Best for |
|---|---|---|---|
index() | Left (first match) | Raises ValueError | Text that must be present |
find() | Left (first match) | Returns -1 | Text that may be missing |
rindex() | Right (last match) | Raises ValueError | Last occurrence that must exist |
rfind() | Right (last match) | Returns -1 | Last occurrence that may be missing |
in operator | Anywhere | False | Only a yes/no answer, no position |
Handling ValueError when the substring is missing
If the text comes from a user or a file, a miss is normal, not a bug. Either test with in first (see checking if a string contains a substring), use find(), or wrap the call in try/except ValueError. Catching the error keeps the happy path short and avoids searching the string twice. The ValueError lesson explains this error in general.
Examples you can run
Press Run, then edit the code and run it again.
Find the first position of a substring
index() gives the starting position of the first match, and rindex() the starting position of the last one.
text = "banana"
print(text.index("an"))
print(text.index("an", 2))
print(text.rindex("an"))Expected output1
3
3
Split an email address at the @ sign
Because the email must contain @, index() is a natural fit. The slices on either side of the position give the user name and the domain.
email = "asha@example.com"
at = email.index("@")
print(email[:at])
print(email[at + 1:])Expected outputasha
example.com
Catch the error for a missing substring
A missing substring raises ValueError; the message is substring not found.
filename = "report.txt"
try:
pos = filename.index("-")
print("Dash at", pos)
except ValueError as err:
print("Error:", err)Expected outputError: substring not found
Common mistakes
Searching with the wrong letter case
✗ Wrong
title = "Python Basics"
print(title.index("basics"))✓ Right
title = "Python Basics"
print(title.lower().index("basics"))index() is case sensitive. Lower-case both sides, or search with the exact case.
Expecting -1 for a missing substring
✗ Wrong
city = "Pune"
if city.index("x") == -1:
print("not found")✓ Right
city = "Pune"
if city.find("x") == -1:
print("not found")The -1 convention belongs to find(). Use find() for a quiet miss, or catch ValueError.
Reading the result as relative to start
✗ Wrong
s = "ab-cd-ef"
i = s.index("-", 3)
print(s[3 + i:])✓ Right
s = "ab-cd-ef"
i = s.index("-", 3)
print(s[i:])The returned index is absolute. Use it as is.
Python String index() Method: questions people ask
What is the difference between index() and find() in Python?
index() raises ValueError when the substring is missing, while find() returns -1. Both return the same position when the text is found, so choose by how you want a miss handled.
Does str.index() return the first or the last occurrence?
It returns the first occurrence, counting from the left. Use rindex() to get the last occurrence instead.
How do I find all positions of a substring in Python?
Call index() in a loop with a growing start argument, or loop with enumerate and compare. A single index() call only gives the first match.
Keep learning
Step-by-step lessons:
Python StringsPython String Methods
Related:
Python String find() MethodPython String count() MethodHow to Check if a String Contains a Substring in PythonPython Slicing
More in string methods:
Python String split() MethodPython String join() MethodPython String strip() MethodPython String lstrip() MethodPython String rstrip() MethodPython String replace() MethodPython String upper() MethodPython String lower() Method See all →