I am trying to compare two strings, one downloaded, one from a file, but the if-statement returns always false, even if the strings 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...
json.loads
translates the data to Python types. You're looking at an integer and comparing it to a string.
Instead of just print current_xkcd
, try print repr(current_xkcd)
or print type(current_xkcd)
, and do the same for downloaded_xkcd
.
Your specific problem is that you are not even comparing two strings to start with.
Json is a rich serialization protocol, and when you do json.loads
with the downloaded data, whatever is numeric 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, a string containing the "2" character does not compare equal the numeral 2. Just convert the number you've recorded in the file in an integer as well -so you are able to make the comparison:
downloaded_xkcd = int(file.read().strip())
But them, you might as well just store in the file a json representation of your data as well, or use "shelve" or "pickle" to store proper serialized data in your file, instead of doing it by hand - which leads to manual conversion strategies like your ".replace(...)" and mine "strip()" - that can (and will) fail in a lot of corner cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With