我試圖比較兩個字符串,一個是從文件中下載的,一個是if語句返回總是false,即使字符串相等。如果我在python中比較兩個字符串,即使它們是相同的,我也會得到false
我做錯了什麼? 這是Python中的錯誤嗎?
代碼:
#!/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..."
輸出:
1515
1515
Downloading xkcd...
也許在字符串中有一些祕密隱藏的空白字符。試試'print repr(current_xkcd)'和'print repr(downloaded_xkcd)'來查看是否有任何標籤或任何顯示。 – Kevin
像凱文說的那樣,我打賭最後有一個'\ r'。 – Jkdc
打印'type(current_xkcd)'和'type(downloaded_xkcd)'。你可能有一個字符串和一個unicode字符串。 –