If I compare two strings in python I get false even though they are the same

I am trying to compare two lines, one loaded, one from a file, but the if-statement always returns false, even if the lines are equal.

Am I doing something wrong? Is this a bug in Python?

code:

#!/usr/bin/python
import json
import urllib2


jsonstring = urllib2.urlopen("https://xkcd.com/info.0.json").read()
j = json.loads(jsonstring)
current_xkcd = j['num']
print current_xkcd
with open ("xkcd.num", "r") as file:
        downloaded_xkcd = file.read().replace('\n', '')
print downloaded_xkcd

if current_xkcd == downloaded_xkcd:
        print "Already got latest xkcd"
else:
        print "Downloading xkcd..."

      

Output:

1515
1515
Downloading xkcd...

      

+3


source to share


4 answers


json.loads

converts data to Python types. You are looking at an integer and comparing it to a string.



print current_xkcd

Try print repr(current_xkcd)

or instead print type(current_xkcd)

, and do the same for downloaded_xkcd

.

+9


source


Your specific problem is that you are not even comparing the two strings to begin with.

Json is a rich serialization protocol, and when you do json.loads

with the loaded data, any numeric number becomes a number of the appropriate type:

>>> import json
>>> import urllib2
>>> jsonstring = urllib2.urlopen("https://xkcd.com/info.0.json").read()
>>> j = json.loads(jsonstring)
>>> type(j["num"])
<type 'int'>

      



And in Python, unlike PHP, Javascript, shellscript, the string containing the character "2" is not compared to the number 2. Just convert the number you wrote to the file to an integer, as you can do the comparison:

downloaded_xkcd = int(file.read().strip())

      

But they can also just store a json representation of your data in a file, or use "shelve" or "pickle" to store the correct serialized data in your file, instead of doing it manually - leading to manual conversion strategies like yours ".replace (...)" and my "strip ()" - which can (and will) fail in many corner cases.

+3


source


OK, I found the problem.

json.loads()['num']

returned int instead of string.

fixed it by changing to current_xkcd = str(j[num])

+2


source


Have you even tried string.strip () for removing whitespace from a string? so try this

current_xkcd = current_xkcd.strip()
downloaded_xkcd = downloaded_xkcd.strip()

      

before comparing them

+1


source







All Articles