1

I have this code:

afile = "name.txt"
f = open(afile,"r")
content = f.readlines()
f.close()
correct = content[1]
answer = raw_input()
if answer == correct:
    print 'True'

Let say that, because of the name.txt, content[1] is George and then I run the code and I type George for answer. Why I won't get True? Why answer and correct are not the same?

2 Answers 2

6

The data you read includes newlines; strip those from the lines first:

if answer == correct.strip():

which removes all whitespace from the start and end of a string. If whitespace at the start or end is important, you can remove just newlines from the end with:

if answer == correct.rstrip('\n'):
Sign up to request clarification or add additional context in comments.

1 Comment

It might be prudent to also use .lower() if capitalization isn't important.
0

Rewritten a bit:

def get_file_line(fname, line_num):
    with open(fname) as inf:
        try:
            for _ in range(line_num + 1):
                line = inf.next()
            return line.rstrip('\r\n')
        except StopIteration:
            return None

if answer == get_file_line('name.txt', 1):
    print('True')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.