user3267646
user3267646

Reputation: 11

Equality of Strings in Python

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?

Upvotes: 1

Views: 81

Answers (2)

Hugh Bothwell
Hugh Bothwell

Reputation: 56624

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')

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121276

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'):

Upvotes: 6

Related Questions