Python:在字符串中查找子字符串,但返回True或False而不是索引位置

2024-06-16 10:03:30 发布

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

我需要检查子字符串是否是特定字符串的一部分。子字符串是“AAA”,如果在给定字符串中找到它,它必须返回True。如果它不在字符串中,则必须返回False

def isResistent(virus):
    gen = "AAA"
    if gen in virus:
        print("True")
    else:
        print("False")

isResistent('GCAAGCTGGTCGTGAAAGCT')

它返回True或False,但除了True或False之外,它首先给出索引号或其他内容。当我多次运行该程序时,它返回:

输出:

^{pr2}$

有可能只打印真假吗?在


Tags: 字符串in程序falsetrue内容ifdef
2条回答

如果使用return,则函数工作正常:

def isResistent(virus):
    gen = "AAA"
    if gen in virus:
        return True
    else:
        return False

>>> isResistent('GCAAGCTGGTCGTGAAAGCT')
True
>>> isResistent('GCAAGCTGGTCGTGGCTGCT')
False

我还将包含gen作为函数参数,以便您将来可以测试"AAA"之外的其他子字符串:

^{pr2}$

你的函数应该是return 'AAA' in virus。在

def isResistent(virus):
    return 'AAA' in virus

>>> isResistent('GCAAGCTGGTCGTGAAAGCT')
True

相关问题 更多 >