在Python中比较两个字符串时出现逻辑错误

2024-04-20 02:51:02 发布

您现在位置: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库将列表格式的字符串转换为列表数据类型。
控件永远不会进入最后一个如果,为什么会发生这种情况?控制如何进入if?即使两个字符串相同,控件也不会进入if。为什么会这样?你知道吗

“这个”符号.txt“文件包含一些行,所有行都以列表格式存储。ast语句正在将这些行转换为列表数据类型。你知道吗

编辑:
我有问题了。显然,ast语句在将string转换为list dataype时添加了一些额外的空格,这导致了if条件的伪造。我改变了if条件:

if var1 in var2:
  #do my job

Tags: inforiflinelocationfrfindast
1条回答
网友
1楼 · 发布于 2024-04-20 02:51:02

如果条件为true,则If语句中的代码将绝对执行。你可以肯定。因此,条件不能是真的。如果不确切地知道你的数据看起来像什么,就不可能确切地知道。最有可能的是,这些值看起来是相同的,但它们根本不可能是相同的。你知道吗

所以,从两个值不相等的前提开始,回答“如果它们不相等,为什么它们不相等?”。例如,您可以打印出每个变量的类型、长度,也可以编写一个小函数,一次比较一个字节,看看哪个字节不同。可能有一个看不见的字符(可能是前导或尾随空格,或者是控制字符,如回车符),或者有一些非常相似的可见字符(如数字1和小写L,或者大写O(oh)和数字0(零))。你知道吗

相关问题 更多 >