[英]Logical error in comparing two strings in Python
我有一個任務,使用我想要的任何語言構建一個兩遍匯編程序。 我選擇了python。 除了一個簡短的問題外,它對我有好處。
我使用.asm輸入文件構建了一個符號表。 然后我使用符號表來創建目標代碼。 我的代碼如下:
import re,os
import ast
fr=open("2input.asm","r")
fw=open("symbol.txt","r+")
objFile=open("symbol1.txt","w")
str2=fr.readline() #reads lines in file
temp=""
str1="" #used for splitting original string
var=""
var1=""
printstr=""
location=map(int, re.findall('\d+',str2)) #extracts location in the form of string and then converts it to integer
loc=location[0] #converts location from list form to integer form
for line in fr: #creates a symbol table
str2=line
loc=loc+1
if str2.find(":")!=-1:
str1=str2.split(":")
str1.append(str(loc))
print>>fw, str1
elif str2.find("DC")!=-1:
str1=str2.split("DC")
str1.append(str(loc))
print>>fw, str1
elif str2.find("DS")!=-1:
str1=str2.split("DS")
str1.append(str(loc))
print>>fw, str1
#symbol table created
fw.seek(0)
fr.seek(0)
for line in fr: #creates object file
str2=line
if str2.find("READ")!=-1:
str1=str2.split()
var=str1[1]
for line in fw:
var1=ast.literal_eval(line)
var2=var1[0]
if var==var2: #it never goes in this if even if the condition is true
printstr="rohit"
print>>objFile, printstr
fw.close()
在最后一個if條件中,我使用ast庫將列表格式的字符串轉換為list數據類型。
控制永遠不會進入最后一次,為什么會發生這種情況? 怎么控制進入if? 即使兩個字符串都相同,控件也不會進入if。 為什么會這樣?
“symbol.txt”文件包含一些行,所有這些行都以列表格式存儲。 這些行由ast語句轉換為list數據類型。
編輯:
我遇到了問題。 顯然,ast語句在將字符串轉換為list dataype時添加了一些額外的空格,導致偽造if條件。 我改變了if條件:
if var1 in var2:
#do my job
如果條件為真,那么if語句中的代碼絕對會執行。 你可以肯定這一點。 因此,條件根本不應該是真實的。 如果不確切知道您的數據是什么樣子,就無法確切知道。 很可能這些值看起來相同,但它們根本不可能。
因此,從價值不相等的前提開始,回答“如果它們不相等,為什么它們不相等?”的問題。 例如,您可以打印出每個變量的類型,每個變量的長度,或者您可以編寫一個小函數,一次比較一個字節,以查看哪個不同。 可能是視覺上看不到的隱形字符(可能是前導或尾隨空格,或者可能是回車等控制字符),或者是非常相似的可見字符(例如數字1和小寫字母) L,或大寫字母O(oh)和數字0(零))。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.