Skip to main content
 首页 » 编程设计

python之如何尽快找到另一个字符串中的特定字符串

2025年05月04日21kenshinobiy

我想知道是否有更好/更好/更快的方法来解决以下问题。

Return True if the given string contains an appearance of "abc" where the abc is not directly preceded by a period (.). So "qabc" counts but "r.abc" does not count.

我的解决方案是:

def abc_there(string): 
    tmp = 0 
    for i in xrange(len(string)): 
        if string[i:i+3] == "abc" and string[i-1] != ".": 
            tmp += 1 
    return tmp > 0 

编辑:

澄清一下:

.abc"--> 错误

.abcabc"--> 正确

只有句号右边的实例会被删除。

请您参考如下方法:

正则表达式是执行此操作的完美工具:

>>> import re 
# Test if it contains a match 
>>> bool(re.search(r'(?:^|[^.])(abc)', 'testabc funcabc')) 
True 
>>> bool(re.search(r'(?:^|[^.])(abc)', '.abc')) 
False 
 
# Count the number of occurrences 
>>> re.findall(r'(?:^|[^.])(abc)', 'abc testabc func.abc') 
['abc', 'abc'] 
>>> len(re.findall(r'(?:^|[^.])(abc)', 'abc testabc func.abc')) 
2 

参见 Python documentation on the re module了解更多详情。