Python String index() Method
By Lenin Mishra
If you prefer to watch Youtube videos over reading blogs, check out our video on Python strings here.
Difference between index()
and find()
in Python
Similar to find() method in Python, the index()
method finds the first occurence of a certain value.
If the value is not found, it raises a ValueError
exception. The find()
method in Python on the other hand, returns -1, if the value is not found.
The index()
method is not case sensitive.
Syntax of index()
method
string.index(value, start end)
value: The value to search for(Required)
start: The integer position to start the search. Default is 0.(Optional)
end: The integer position to end the search. Default is the end of the string.(Optional)
Example 1
Code
str1 = "Pylenin loves Python"
print(str1.index("Python"))
Output
14
The substring Python
occurs first time at position 14 in the string.
Example 2 - Check for case sensitivity
Code
str1 = "Pylenin loves Python"
print(str1.index("python"))
Output
ValueError: substring not found
Example 3 - Search for a non-existing string.
Code
str1 = "Pylenin loves Python"
print(str1.index("Apples"))
Output
ValueError: substring not found
Example 4 - Search a substring s1
in a specific portion of string s2
.
Code
s2 = 'I like reading Pylenin blogs on Python'
s1 = 'Python'
# Search between position 10 and 20
try:
print(s2.index(s1, 10, 20))
except Exception as e:
print(e.__class__, e)
print(f"'{s1}' occurs at index {s2.index(s1)}")
Output
<class 'ValueError'> substring not found
'Python' occurs at index 32
As you can see, the substring Python
occurs at index 32, but we are searching within the index 10 and 20.
Because, we are using a try-except
block, ValueError
exception is not being raised. Learn more about Python Exceptions and ways to handle them.
Check out other commonly used Python string methods.
Related Articles
- How to create a string in Python?
- How to access characters in a Python string?
- How to replace characters in a string in Python?
- How to concatenate strings in Python?
- How to iterate through a string in Python?
- Check if a Substring is Present in a Given String in Python
- Escape sequences in Python String
- Python String Formatting - The Definitive Guide