python中如何用IF语句匹配两个相等的字符串

2024-04-19 05:01:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我的Python代码:

import re

output = "your test contains errors"    

match2 = re.findall('(.* contains errors)',output)
mat2 = "['your test contains errors'] "

if match2 == mat2:
    print "PASS"

在上面的python程序中,'match2'和mat2中有字符串。如果它是一样的,它应该打印通过。在

如果我运行这个程序,我不会得到任何错误。如果我打印“match2”和“mat2”的输出相同。但如果我使用“if match2==mat2”则不会打印为“PASS”。在

谁能帮我修好这个吗。在

提前谢谢。在

谢谢

库马尔。在


Tags: 代码testimport程序reoutputyourif
2条回答

如果要测试字符串匹配,则应比较字符串并使用搜索足够:

output = "your test contains errors"

match2 = re.search('(.* contains errors)',output)
mat2 = 'your test contains errors'
if match2 and match.group() == mat2:
    print "PASS"

findall也将返回多个匹配项,因此即使使用mat2 = ['your test contains errors']也会在存在多个匹配项时失败。在

在上面的程序中,如果字符串和字符串都是基于matchex>的方法比较的,那么这两种方法都是基于matchex>的。如果它是一样的,它应该打印通过。是的,那么您根本不应该使用regex:

^{pr2}$

regex相当于str.startswith,因此一个简单的:

if output.startswith(mat2):
    print "PASS"

也一样。在

您的regex方法将匹配子字符串:

import re

output = "foo your test contains errors"

match2 = re.findall('(.* contains errors)',output)

print(match2)

输出:

 ['foo your test contains errors']

因此,使用正则表达式获得匹配的唯一方法是字符串以your test ...开头,str.startswith可以在不需要正则表达式的情况下进行测试。在

因此,如果你想找到字符串是否以'your test contains errors'开头,如果你只想知道contains errors在字符串中,请使用if "contains errors" in output,或者等效的方法是使用if match2:,使用search来查找{}是否在字符串的前面加上任何字符。在

您还可以使用if 'your test contains errors'来查找子字符串是否在字符串中的任何位置,但这不是regex所做的。在

^{}返回列表,而不是字符串。所以mat2也应该是一个列表:

mat2 = ['your test contains errors']

如果要检查字符串中的your test contains errors,可以使用in运算符:

^{pr2}$

相关问题 更多 >