python中的字符串相等
我试图检查两个字符串是否相等,但我的代码似乎无法正常工作:python中的字符串相等,python,string,Python,String,我试图检查两个字符串是否相等,但我的代码似乎无法正常工作: listes = [] for row in my_lines: split = re.split(r' +', row) print split[0], ":size of the split: ", len(split) if str(split[0]) == '5': print "...." if语句之前的“我的打印”中的打印消息如下: '5' :size of the split:
listes = []
for row in my_lines:
split = re.split(r' +', row)
print split[0], ":size of the split: ", len(split)
if str(split[0]) == '5':
print "...."
if语句之前的“我的打印”中的打印消息如下:
'5' :size of the split: 3
'4' :size of the split: 4
'6' :size of the split: 3
'6' :size of the split: 4
'F' :size of the split: 4
'6' :size of the split: 4
'F' :size of the split: 4
'6' :size of the split: 4
但是if语句不起作用。这里可能出了什么问题?这是因为您的
拆分[0]
内容本身已根据您提到的输出将“
作为字符串的一部分。您需要进行如下比较:
if str(split[0]) == "'5'":
# ^ ^ single quotes here
或者,从行的开头和结尾删除”
,如下所示:
if str(split[0])[1:-1] == "5":
# ^ ^ remove first and last character from string
这是因为根据您提到的输出,
split[0]
内容本身将'
作为字符串的一部分。您需要进行如下比较:
if str(split[0]) == "'5'":
# ^ ^ single quotes here
或者,从行的开头和结尾删除”
,如下所示:
if str(split[0])[1:-1] == "5":
# ^ ^ remove first and last character from string
您的
拆分[x]
似乎包含一个格式为“'x'
”的字符串,但您只是将其与“x”
进行比较。看起来该字符串实际上是带有单引号和空格的'5'
。是的,您是对的。谢谢你的回答!您的拆分[x]
似乎包含一个格式为“'x'
”的字符串,但您只是将其与“x”
进行比较。看起来该字符串实际上是带有单引号和空格的'5'
。是的,您是对的。谢谢你的回答!