Python index ValueError: substring not found
Often programmers with different background are confused by error:
ValueError: substring not found
when they are trying to find character in a string like:
mystring = 'This is a simple string test].'
begin = mystring.index('[')
The behavior is not expected by many programmers to have an error for this search. A more expected behavior is to get -1 or not found instead of error. This can be done by using method find():
mystring = 'This is a simple string test].'
begin = mystring.find('[')
print(begin)
result:
-1
Behavior of the functions is the same if a substring is found.
Another difference of the two functions is that index is available for lists, tuples while found is only for strings.