.index()
Anonymous contributor
Anonymous contributor3071 total contributions
Anonymous contributor
Published Oct 19, 2021Updated Nov 1, 2021
Contribute to Docs
The .index()
string method searches through a string variable for the occurrence of a pattern or a substring.
If the substring is not found, a ValueError
will be raised.
Syntax
string.index(pattern, start, end)
In the above syntax for the .index()
method:
pattern
(Required): The pattern or substring to search for.start
(Optional): The starting index ofstring
to search. The default is 0.end
(Optional): The index of the slice ofstring
to search up to, non-inclusive. The default is end of the string.
Example 1
Use .index()
method to search for the occurrence of 'Python'
in the string variable my_string
:
my_string = 'Learning Python is fun!'index = my_string.index('Python')print(index)# Output: 9
The starting index of the substring 'Python'
is 9.
Example 2
Use .index()
method to search for the occurrence of 'Coding'
in the string variable my_string
:
my_string = 'Learning Python is fun!'my_string.index('Coding')
There will be an error:
ValueError: substring not found
Codebyte Example
Use .index()
method to search for the occurrence of 'code'
in a slice of the string variable my_string
(i.e. from the character at index 8 up to, but not including, the character at index 16):
All contributors
- Anonymous contributorAnonymous contributor3071 total contributions
- BalaPriyaC6 total contributions
- Anonymous contributor
- BalaPriyaC
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.