Apex
Apex

Reputation: 1096

How to ignore returning None in re.search Python

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?

Upvotes: 2

Views: 1870

Answers (1)

Ryszard Czech
Ryszard Czech

Reputation: 18621

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.

Upvotes: 1

Related Questions