logo

String index

The function .index() returns the index (position) of a substring in a string (if found). Returns exception if not found.
It’s case sensitive. If you want to know at which character a substring inside a string starts, you need this function.

Syntax


The format is:


str.index(string)




or you can use this format



str.index(string,start,end)



Related Course:
Python Programming Bootcamp: Go from zero to hero


Parameters



Parameter
string The string to search.
start Index to start searching (optional).
end Ending index (optional).

Example


str = "Tip of the day: "
print( str.index("Tip") )

Result:

0

Example #2


str = "Tip of the day: "
print( str.index("Tip",5) ) # throws exception

Result:


Traceback (most recent call last):
File “tmp.py”, line 2, in
print( str.index(“Tip”) )
ValueError: substring not found

BackNext





Leave a Reply: