Ryan Barrett
Ryan Barrett

Reputation: 25

Can two identical strings not be equal to each other in Python?

Below is the code in question:

def search():
        name = enter.get()
        print(name)
        name = name.lower()
        data = open("moredata.txt")
        found = False
        results = str()

        for line in data:
            record = line.split("|")
            record[0] = str(record[0])
            print("'" + name + "'" "---" + "'" + record[0] + "'")

            if record[0] == name:
                found = True
                line = str(line)
                results += line
                results = str(results).lstrip(' ')

                continue
            else:
                found = False
                continue
        if not found:
            print("No results found")

        else:
            print("These items match your search query:\n")
            print(results)
            # print(results)
            print('\n---------------------------------\n')

In the text file I am using, pieces of information are separated by '|' and the function splits each piece into an array (I think?) and compares just the first value to what I put in the search bar.

I have used other text files with the same exact function, it works just fine: it verifies that the two strings are equal and then displays the entire line of the text file corresponding to what I wanted. However, when I search "a" which should register as equal to "a" from the line a|a|a|a|a|a in my text file, it doesn't. I know this is going to bite me later if I don't figure it out and move on because it works in some cases.

The line

print("'" + name + "'" "---" + "'" + record[0] + "'")

results in

'a'---'a'
'a'---'a'
'a'---'b'

when compared to lines

a|a|a|a|a|a
a|a|a|a|a|a
b|b|b|b|b|b

There are no empty lines between results, and both variable types are str().

Upvotes: 0

Views: 238

Answers (2)

jfowkes
jfowkes

Reputation: 1565

Your found variable is being overwritten on each iteration of the loop. Therefore it will only be True if the last result matches.

You don't actually need your found variable at all. If there are results, your results variable will have data in it and you can test for that.

Upvotes: 1

Benjamin James Drury
Benjamin James Drury

Reputation: 2383

The continue in your if statement in the loop is what's causing the problem as it should be a break.

Your program is finding it, but it's then being overwritten by the last iteration. Once your program has found, you should either never set found back to false, or preferably just cease the iteration altogether.

I would wager the other files you've tested with all end with the name that you were looking for, and this one is causing a problem because the name you're looking for isn't at the end.

Additionally, though technically not a problem, the other continue under the else in the for loop isn't necessary.

Upvotes: 1

Related Questions