문제

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?

도움이 되었습니까?

해결책

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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top