umbro_tracksuit
umbro_tracksuit

Reputation: 141

How can I search a string for any occurrence of substring (including partial matches) in python?

I am trying to write a program which will search through a series of strings and return true if any part of a substring is found.

For example, say the substring I am interested in is:

GATCGATC

The program should return True for:

GGTGGATCGATC

And should also return true for (because it ends with GATC):

GGTGTTTTGATC

So far I have:

def matchpat(str1, str2):
    '''Find a pattern in a string'''
    if str1 in str2:
        return True
    else:
        return False

This function works, but only if the whole pattern is present, it will return False for partial matches.

Upvotes: 1

Views: 259

Answers (3)

Philiong
Philiong

Reputation: 358

Hi i made this code which works. You can change it to be more dynamical with the variables

text = 'GGTGGATCGATC'
lookingFor = 'GATCGATC'

def method():
  print('in check')
  if lookingFor in text:
    return true
  else:
    return false

def main():
  method()
  if __name__ == "__main__":

If you want to make the method take in input you can pass it in the method definition:

def method(text, lookingFor)

Upvotes: 2

Venkataraman R
Venkataraman R

Reputation: 13009

You can use re module to do that

import re

patterntomatch = "GATCGATC"
patterntomatch = "[{0}]".format(patterntomatch)

TextTomatch = "This is something"

matchObj = re.match(patterntomatch,TextTomatch,re.I)

if matchObj:
    print ("match found")
else:
    print("no match found")

Upvotes: 0

Nick
Nick

Reputation: 3845

I have used a library called Fuzzywuzzy for a similar problem, which worked well for my requirements and may help.

It uses Levenshtein distance metric to compare the strings.

Upvotes: 0

Related Questions