在字符串中查找“xyz”,但不查找“.xyz”

2024-04-26 05:41:08 发布

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

我试图编写一个布尔值,如果'xyz'在字符串中,但前面没有“.”的话,它是真的

我的问题是,我可以让大多数用例正常工作,但如果有一个带有匹配项的“.xyz”,那么就不行了,我认为这应该包含在布尔值的假边中

我的代码是:

def xyz_there(s):
  return (('xyz' in s and '.xyz' not in s) or ('xyz' in s and '.xyz' in s))

用例:(调用-预期结果-我得到的结果)


xyz_there('abcxyz') → True  True
xyz_there('abc.xyz') → False    True    
xyz_there('xyz.abc') → True True    
xyz_there('abcxy') → False  False   
xyz_there('xyz') → True True    
xyz_there('xy') → False False   
xyz_there('x') → False  False       
xyz_there('') → False   False   
xyz_there('abc.xyzxyz') → True  True
xyz_there('abc.xxyz') → True    True    
xyz_there('.xyz') → False   True    
xyz_there('12.xyz') → False True        
xyz_there('12xyz') → True   True    
xyz_there('1.xyz.xyz2.xyz') → False True


Tags: orand字符串代码infalsetruereturn
3条回答

这对于正则表达式来说可能是最容易的,可以使用.的负查找来查找xyz

import re

def xyz_there(s):
    return re.search(r'(?<!\.)xyz', s) is not None

如果不能使用正则表达式,可以将s的每4个字符的子字符串与*xyz进行比较,其中*可以是.以外的任何字符:

def xyz_there(s):
    return s.startswith('xyz') or any(s[i] != '.' and s[i+1:i+4] == 'xyz' for i in range(0, len(s)-2))

any循环可以展开为一个简单的for循环:

def xyz_there(s):
    if s.startswith('xyz'):
        return True
    for i in range(0, len(s)-2):
        if s[i] != '.' and s[i+1:i+4] == 'xyz':
            return True
    return False

你喜欢简单优雅的代码吗

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

要检查解决方案,请以这种方式执行测试

def tests():
    assert xyz_there('abcxyz') is True # → True  True
    assert xyz_there('abc.xyz') is False # → False    True    
    assert xyz_there('xyz.abc') is True # → True True    
    assert xyz_there('abcxy') is False # → False  False   
    assert xyz_there('xyz') is True # → True True    
    assert xyz_there('xy') is False # → False False   
    assert xyz_there('x') is False # → False  False       
    assert xyz_there('') is False # → False   False   
    assert xyz_there('abc.xyzxyz') is True # → True  True
    assert xyz_there('abc.xxyz') is True # → True    True    
    assert xyz_there('.xyz') is False # → False   True    
    assert xyz_there('12.xyz') is False # → False True        
    assert xyz_there('12xyz') is True # → True   True    
    assert xyz_there('1.xyz.xyz2.xyz') is False # → False True

然后调用tests()

基本解释:

请记住,每当字符串“.xyz”出现时,字符串“xyz”也会同时出现,因为“.xyz”包含在“.xyz”中。因此,要使它有一个前面没有“.”的额外“xyz”,必须有比“.xyz”子字符串更多的“xyz”子字符串

让我们看一个失败的测试

xyz_there('abc.xyz')

这应该是错误的,并且正在成为现实

我们可以插入计算表达式的结果,看看逻辑是如何工作的

(('xyz' in s and '.xyz' not in s) or ('xyz' in s and '.xyz' in s))

((True and False) or (True and True))

((False) or (True))

((True))

当字符串包含“.xyz”时,or右侧的表达式将始终为true,因此在这种情况下,表达式将始终为true,但该字符串不应符合true返回值的条件

不管怎样,只查看字符串中是否出现“xyz”和“.xyz”是在错误的轨道上。如果字符串中多次出现“xyz”,则必须分别检查每个“xyz”前面是否有“.”,并且必须查看所有这些检查的结果,以查看是否有“xyz”前面没有“.”

相关问题 更多 >