Skip to main content
 首页 » 编程设计

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

2025年05月04日21oomusou

我正在练习我的 python 编码 website .这就是问题

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 

请您参考如下方法:

网站似乎不允许import,所以最简单的可能是:

'xyz' in test.replace('.xyz', '') 

否则,您可以在断言后面使用带有否定外观的正则表达式:

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