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...
source to share
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.
source to share