Python 检查特定字符串是否出现在另一个字符串中

Python 检查特定字符串是否出现在另一个字符串中,python,debugging,Python,Debugging,我正在这方面练习python编码。这就是问题所在 Return True if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not. xyz_there('abcxyz') → True xyz_there('abc.xyz') → False xyz_th

我正在这方面练习python编码。这就是问题所在

Return True if the given string contains an appearance of "xyz" where the xyz is 
not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not. 

xyz_there('abcxyz') → True
xyz_there('abc.xyz') → False
xyz_there('xyz.abc') → True
这是我的代码,不知什么原因,我没有通过所有的测试用例。我调试它有问题

def xyz_there(str):

    counter = str.count(".xyz")
    if ( counter > 0 ):
        return False
    else:
        return True

网站似乎不允许导入,因此最简单的可能是:

'xyz' in test.replace('.xyz', '')
否则,您可以使用带有否定look-behind断言的正则表达式:

import re

tests = ['abcxyz', 'abc.xyz', 'xyz.abc']
for test in tests:
    res = re.search(r'(?<!\.)xyz', test)
    print test, bool(res)

#abcxyz True
#abc.xyz False
#xyz.abc True
重新导入
测试=['abcxyz','abc.xyz','xyz.abc']
对于测试中的测试:

res=re.search(r’(?该网站似乎不允许导入,因此最简单的可能是:

'xyz' in test.replace('.xyz', '')
否则,您可以使用带有否定look-behind断言的正则表达式:

import re

tests = ['abcxyz', 'abc.xyz', 'xyz.abc']
for test in tests:
    res = re.search(r'(?<!\.)xyz', test)
    print test, bool(res)

#abcxyz True
#abc.xyz False
#xyz.abc True
重新导入
测试=['abcxyz','abc.xyz','xyz.abc']
对于测试中的测试:

res=re.search(r’(?查看是否存在不属于
xyz
。xyz
的一种方法是计算
xyz
的数量,计算
.xyz
的数量,然后查看第一个是否多于第二个。例如:

def xyz_there(s):
    return s.count("xyz") > s.count(".xyz")

它通过了网站上的所有测试。

查看是否有
xyz
不属于
.xyz
的一种方法是计算
xyz
的数量,计算
.xyz
的数量,然后查看第一个是否多于第二个。例如:

def xyz_there(s):
    return s.count("xyz") > s.count(".xyz")

它通过了网站上的所有测试。

您的代码对字符串“abc”返回True。@OmriBarel我刚才链接到了错误的页面,请看一看。againI只是指您的代码。它对“abc”返回True,我不确定这是否是您想要的。您的代码对字符串“abc”返回True@OmriBarel我刚才链接到了错误的页面,请看一看,againI只是引用了您的代码。它返回的“abc”为True,我不确定这是您想要的。