Confusion with using string.find method

The definition states the first argument is the substring then followed by two optional arguments, start index and end index. Here is an example of my issue…

spam = ‘0100’

print(spam.find(‘1’,0,1))

This results in -1 or that the it cannot find ‘1’ within the indices 0 and 1, but the character 1 is in that range at position 1. What am I missing?

Ranges and slices in Python are always open on the right hand side:

>>> spam = '0100'
>>> spam[0:1]
'0'

find conforms to this, so in your code spam[1] is not part of the searched substring. See Built-in Types — Python 3.9.2 documentation which states for find: “Return the lowest index in the string where substring sub is found within the slice s[start:end] .”

1 Like

Thank you for clarifying. This was helpful.