如何按字符分析字符串字符时如何检查匹配?

时间:2018-02-01 13:38:50

标签: python

我正在尝试编写汇编程序,我的方法如下:首先,我得到程序,将其拆分为行。在那之后,我单独处理每一行,将每一行分成包含所有内容的字符,我现在卡住了,因为我不知道如何检查匹配,例如:我将如何检查操作码" LOAD"寄存器" R1"和数据值" 18"在诸如[" L"," O"," A"," D"," "," R"," 1",","," 1"," 8" ]?请帮助表示感谢。

2 个答案:

答案 0 :(得分:1)

在将行拆分为字符之前,您可以将其拆分为如下列表中的单词。然后,if语句可以检查列表中的项目。

x=["This", "apple","is","red"]
if "This" in x:
    print "yes"

更新了以下评论的答案。

line="MD=D+1"
if "MD" in line:
    print "Do something"

更新以使命令脱节。

line="MD=D+1"
if "MD" in line:
    print line.split("MD")
    command=line.split("MD")[1] #get second element in list
    print command
    #now you can parse command to do something with it. 

答案 1 :(得分:0)

首先,你必须在一个新的str中连接字符串。 然后,您可以在字符串上使用split方法来创建charList。

  

str1 ='LOAD',str2 ='R1',str3 = '8

strN = str1 + " " + str2 + " " + str3
result = strN.split()
print(result)