How to ignore returning None in re.search Python

Viewed 711

I have a string and a list of two elements that by using a custom def I yield different versions of each element by one mismatch - then I do a loop to perform re.search and if any version of elements founded then print that part on the main string.

My code is working but not my challenge is to skip None in re.search.

Here is my code:

list=['patterrn1','pattern2']
my_string='something--patterRn1--something'

def idf_one_mismatch(x):
    for i in range(len(x)):
        yield x[:i] + '.' + x[i+1:]

def find_while_mismatch(x,y):
    for i in idf_one_mismatch(x):
        m = re.search(i,str(y))
        if m is not None: 
            return m.group()

for i in list:
    idf1 = find_while_mismatch(i, my_string)
    print(idf1)

The output is:

patterRn1
None

Which the output should skip the None but it does not. How can I achieve that?

1 Answers

First things first, do not use reserved words / builtins as variable names, replace list with some other name.

Second, you get None since your find_while_mismatch returns this value if no match was found during the for loop.

Use

if idf1:
    print(idf1)

if you need to prevent that output.

Related