greenbug
greenbug

Reputation: 158

Comparing string with text file in python

I am trying to compare a string with the text from a text file. For some reason though, it's coming back as not the same even though I've literally copied and pasted the text from the text file to my string. I also checkhow to compare a string with a text file to make sure I was doing it right and I am so I am super confused on why this isn't working.

string = "This is working"
x = open('work.txt').read()
print(string)
print(x)
print(x is string)

The content of the text file is This is working and when I run the code I get the output below

This is working
This is working

False

Edit: I also already tried:

if string == open('work.txt').read():
    print("Working")
else:
    print("Not working")

and that also gives out Not working

Upvotes: 0

Views: 1059

Answers (2)

Anon Coward
Anon Coward

Reputation: 10827

Two issues, as mentioned you should be using == instead of is to check for equality. Also, note the extra line between the second print statements output and your result output. That's because the string you read from the file has a newline in it, so they're not the same string.

If you strip off the newline, they should compare:

string = "This is working"
x = open('work.txt').read().strip()
print(string)
print(x)
print(x == string)

Upvotes: 2

SuperStew
SuperStew

Reputation: 3054

try this instead

print(x == string)

Upvotes: -1

Related Questions