user3457104
user3457104

Reputation: 13

Strings won't compare properly

I'm new to python so excuse any poor code you may find

The problem I'm having is that I'm trying to compare two strings, one from a file and one from user input, to see if they match. However, when comparing what seem to me identical strings, the if statement returns false. I have used the str() function to turn both of the values into strings, but it still doesn't want to play ball.

For reference, the line of the file is two strings, separated by a comma, and the 'question' part is before the comma and the 'answer' after it. At present, both the strings are test strings, and so have the values of 'Question' and 'Answer'

import linecache
def askQuestion(question, answer):
    choice = input(question)
    str(choice)
    if choice == answer:
        print("Correct")
    else:
        print("Bad luck")
file = "C://questions.txt"
text = linecache.getline(file, 1)
question = text.split(",", 1)[0]
answer = text.split(",", 1)[-1]
str(answer)
askQuestion(question, answer)

I am typing in exactly what the file has i.e. capital letters in the right place, for note. I'm sure the answer obvious, but I'm at a loss, so any help would be kindly appreciated.

Thanks!

Upvotes: 1

Views: 188

Answers (1)

Sean Perry
Sean Perry

Reputation: 3886

text = linecache.getline(file, 1)
question = text.split(",", 1)[0]
answer = text.split(",", 1)[-1]

this is more commonly written

text = linecache.getline(file, 1)
question, answer = text.split(",", 1)

The results will be a string. There is no interpretation happening. Also, you need to store the result of str().

my_string = str(number)

By calling str() but not saving it the result is being lost. Not important here, but something to keep in mind.

As Alex mentions in the comment above you are missing the call to strip to remove the newline. How do I know? I tried it in the interpreter.

$ python
>>> import linecache
>>> line = linecache.getline("tmpfile", 1)
>>> line

'* Contact Numbers\n'

See that '\n' there? That is your problem.

Another way would have been to invoke pdb the Python Debugger. Just add

import pdb; pdb.set_trace()

where you want to stop the execution of a Python script.

Good luck.

Upvotes: 2

Related Questions