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

标签 python debugging

我正在练习我的 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

关于python - 检查特定字符串是否出现在另一个字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16778048/

相关文章:

python - Powershell:Webclient 无法上传字符串

python - 正则表达式 获取介于两者之间的一切,Python

python - 如何等待生成的线程在 Python 中完成

debugging - 在反汇编中查找函数

python - 使用 Python 中的 30 年基线计算气候异常

python - 仅当调用字典键时才生成数据

.net - 在调试器下运行时更改程序流程

C++ - 检测越界访问

debugging - valgrind 多重类型抑制

android - 无法在 Jelly Bean 中使用 systrace