Search code examples
pythonstringfind

Unexpected results from Pyhton find() function


I have this string

string = "DLR1=A,B,C,D,E,F,G|DLR2=A,B,C,D,E,F,G|DLR=A,B,C,D,E,F,G|"

And I want to find the indexes of DLR, DLR1 and DLR2.

However, when I use the Python find() function I do not get 3 different indexes as I expect.

From what I understand, the function looks for the first occurrence of my substring (DLR, DLR1, DLR2) and returns the index.

If this is true, I don't understand why DLR and DLR1 have the same starting index but DLR2 has a different one.

What I've tried

When running this code:

string = "DLR1=A,B,C,D,E,F,G|DLR2=A,B,C,D,E,F,G|DLR=A,B,C,D,E,F,G|"

print(string.find('DLR'))

print(string.find('DLR1'))

print(string.find('DLR2'))

Output:

0
0
19

I found that this outputs the expected result:

print(string.find('DLR='))

print(string.find('DLR1='))

print(string.find('DLR2='))

Output:

38
0
19

My question is why does this happen and is this expected?

Edit:

@slothrop gave a nice explanation

string[0:3] is 'DLR', and string[0:4] is 'DLR1'. So both string.find('DLR') and string.find('DLR1')` give 0. But there is no n such that string[0:n] is 'DLR2', so string.find('DLR2') can't be 0


Solution

  • What does str.find()

    The find() method finds the first occurrence of the specified value and returns -1 if the value is not found.

    str.find() documentation:

    Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

    In your first snippet:

    • DLR is at the index 0 (because it's a substring of DLR1)
    • DLR1is at the index 0 too
    • DLR2is at the index 19

    In your second snippet:

    • DLR= is at the index 38
    • DLR1=is at the index 0
    • DLR2=is at the index 19