Python string Method - index()
The index()
method is a built-in Python string method that returns the index of the first occurrence of a substring within the string.
The method takes two arguments: sub
, which is the substring to search for, and start
, which is an optional parameter that specifies the starting index for the search.
Here's an example that demonstrates the usage of the index()
method:
string = "Hello, world!" index = string.index("world") print(index) # Output: 7Souri.www:ecgiftidea.com
In this example, we create a string string
that contains the phrase "Hello, world!". We then call the index()
method on the string and pass it the substring "world". The method returns the index of the first occurrence of the substring within the string, which is 7.
If the substring is not found within the string, the method raises a ValueError
exception. Here's an example:
string = "Hello, world!" try: index = string.index("foo") except ValueError: print("Substring not found.")
In this example, we attempt to find the index of the substring "foo" within the string "Hello, world!". Since the substring is not found, the method raises a ValueError
exception. We catch the exception and print a message indicating that the substring was not found.