find() function in python2.7.5

后端 未结 2 1339
一个人的身影
一个人的身影 2021-01-16 11:21

find(\'asdf\',\'\') finds an empty string in \'asdf\' hence it returns 0. Similarly, find(\'asdf\',\'\',3) starts to sea

相关标签:
2条回答
  • 2021-01-16 11:23

    Because "asdf" without its first four characters still does contain "". A harder check comes into play when the index exceeds the length of the string, but having an index equal to the string is equivalent to "".find().

    0 讨论(0)
  • 2021-01-16 11:24

    Here is how it works:

    0 a 1 s 2 d 3 f 4
    

    When you use 'asdf'.find(sub), it searches those five positions, labeled 0, 1, 2, 3, and 4. Those five. Those five. No more and no less. It returns the first one where 'asdf'[pos:pos+len(sub)] == sub. If you include the start argument to find, it starts at that position. That position. Not one less, not one more. If you give a start position greater than the greatest number in the list of positions, it returns -1.

    In other words, the answer is what I already repeated in a comment, quoting another question answer:

    The last position [for find] is after the last character of the string

    Edit: it seems your fundamental misunderstanding relates to the notion of "positions" in a string. find is not returning positions which you are expected to access as individual units. Even if it returns 4, that doesn't mean the empty string is "at" position 4. find returns slice starts. You are supposed to slice the string starting at the given position.

    So when you do 'asdf'.find('', 4), it starts at position 4. It finds the empty string there because 'asdf'[4:4+len('')]==''. It returns 4. That is how it works.

    It is not intended that str.find has a one-to-one mapping between valid indexes into the actual string. Yes, you can do tons of other indexing like 'asdf'[100:300]. That is not relevant for find. What you know from find is that 'asdf'[pos:pos+len(sub)] == sub. You do not know that every possible index that would return '' will be returned by find, nor are you guaranteed that the number returned by find is a valid index into the string if you searched for an empty string.

    If you have an actual question about some use of this functionality, then go ahead and ask that as a separate question. But you seem to already know how find works, so it's not clear what you're hoping to gain from this question.

    0 讨论(0)
提交回复
热议问题