python

python string indexof - get index of a substring

We can get the index of a substring in a python string using the index() function. We pass the substring as a parameter in the index() function and it returns the index value.

full_str = "Devsheet"

result = full_str.index("vs")

print(result)

# -> 2

In the above code snippet:

1. Defined a string variable full_str that contains a string value.

2. Using String.index() method and passing substring 'vs' as a parameter to it to get the index of the substring.

3. Print the result.

Read more about the python index() function

If the substring could not be found in the string then it will throw ValueError: substring not found. For example, if we use the below code to get the index of substring vst.

full_str.index("vst")

The code will throw the error as 'vst' substring does not exist in the string 'Devsheet'.

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    result = full_str.index("vst")
ValueError: substring not found

Use of String.find() function to get the index of a substring

You can use python exception handling or use the find() function to handle the exception - substring not found. It will return -1 if the substring does not exist inside the string.

full_str = "Devsheet"

result = full_str.find("vst")

print(result)

# -> -1

The code will not throw any exception if the substring cound not be found and return -1. If the substring exists inside the string then it will return the index of substring like index() function.

Was this helpful?