find the first index of a substring in a string in python

You can find the first index of a substring in a string in Python by using the index() method of the string object. Here's an example:

main.py
string = "hello world"
substring = "world"
index = string.index(substring)
print(index)  # Output: 6
101 chars
5 lines

In this example, we define a string and a substring we want to find the position of. We then call the index() method on the string object, passing in the substring as an argument. The return value of this method is the first index of the substring in the string.

Note that if the substring is not found in the string, the index() method will raise a ValueError. To avoid this, you can use the find() method instead, which will return -1 if the substring is not found.

gistlibby LogSnag