Question

I made a function that looks something like this:

def function(input):
    data = input.txt
    A = re.search(r'(re)(ge)(x1)',data).group(2)
    B = re.search(r'(re)(ge)(x2)',data).group(2)
    C = re.search(r'(re)(ge)(x3)',data).group(2)
    return A + "text" + B + C

I am running this within a loop that cycles through many input.txt files. Sometimes, in input.txt, B or C might not be there. When this happens, I get an error:

AttributeError: 'NoneType' object has no attribute 'group'

This appears to have stopped my loop. Is there a way I can make returning B or C optional so that my loop continues to run?

Était-ce utile?

La solution

Just don't automatically call .group(2) for B and C. This assumes that you know you'll always find a match for A.

def function(input):
    data = input.txt
    A = re.search(r'(re)(ge)(x1)',data).group(2)

    gb = re.search(r'(re)(ge)(x2)',data)
    B = gb.group(2) if gb else ""

    gc = re.search(r'(re)(ge)(x3)',data)
    C = gc.group(2) if gc else ""

    return "%stext%s%s" % (A, B, C)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top