Raptor-ZH
Raptor-ZH

Reputation: 17

Python: Finding a substring in a string, but returning True or False instead of the index position

I need to check if a substring is part of a specific string. The substring is 'AAA' and if it is found in the given string, it must return True. If it isn't in the string, it must return False

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

isResistent('GCAAGCTGGTCGTGAAAGCT')

It returns True or False, but besides True or False it first gives the index number or something. When I run the program several times it returns:

Output:

2
True

1
True

2
True

4
True

0 
True

Is it possible to only print True or False?

Upvotes: 0

Views: 13782

Answers (3)

lukout
lukout

Reputation: 1

If you also want to account for lowercase uses like aaa AAa Aaa (etc) which I have found useful if pulling out specific words from a sentence, based on Bill the Lizard's response:

def isResistent(virus):
    return 'aaa' in virus.lower()

>>> isResistent('GCAAGCTGGTCGTGAaAGCT')
True
>>> isResistent('GCAAGCTGGTCGTGAAAGCT')
True

or RoadRunner's:

def isResistent(virus, gen):
    return gen.lower() in virus.lower()

>>> isResistent('GCAAGCTGGTCGTGAAaGCT', 'AAA')
True
>>> isResistent('GCAAGCTGGTCGTGGCTGCT', 'AAA')
False
>>> isResistent('GCAagcTGGTCGTGAAAGCT', 'AGC')
True

Example:

def findWord(string, word):
    """
    Outputs true or false if word is found, can be upper or lower. 
    Does NOT account for punctuation.
    """
    return word.lower() in string.lower()
    
>>> findWord('Is there a WORD here?', 'Word')
True

Upvotes: 0

RoadRunner
RoadRunner

Reputation: 26325

Your function works fine when you use return instead:

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

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

I would also include gen as a function parameter, so you can test other sub strings other than "AAA" in the future:

def isResistent(virus, gen):
    return gen in virus

>>> isResistent('GCAAGCTGGTCGTGAAAGCT', 'AAA')
True
>>> isResistent('GCAAGCTGGTCGTGGCTGCT', 'AAA')
False
>>> isResistent('GCAAGCTGGTCGTGAAAGCT', 'AGC')
True

Upvotes: 1

Bill the Lizard
Bill the Lizard

Reputation: 405965

Your function should just return 'AAA' in virus.

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

>>> isResistent('GCAAGCTGGTCGTGAAAGCT')
True

Upvotes: 6

Related Questions