Tralala
Tralala

Reputation: 283

Python loop if statement exit

I want to find 2 elements in the first page of a pdf file. The elements that start with P and the elements that start with N. Even if 1 element has been found, the search for the other element still needs to be continued.

If P is found, continue searching for N If N is found, continue searching for P When P and N are found, stop searching

I am having troubles with my loops, N is only found if there is no P. I get that there is a issue with the if-statements, but I can't seem to correct it.

    if text is not None:
        p_new = "NoPFound"
        n_new = "NoNFound"
        for line in text.split('\n'):
            #get p
            if line.startswith('P '):
                pieces = line.split()
                p_old = pieces[1]
                p_new = (p_old[7:11]) + (p_old[0:6])
                break
            #get n
            if line.startswith('N '):
                pieces = line.split()
                n_old = pieces[1]                        
                n_new = (n_old[0:15]) + "/" + (n_old[18:20])
                break
    list_parsed_items.append([p_new, n_new])

Upvotes: 0

Views: 41

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54698

Use flags. You have a small state machine.

    if text is not None:
        p_new = None
        n_new = None
        for line in text.splitlines():
            #get p
            if not p_new and line.startswith('P '):
                pieces = line.split()
                p_old = pieces[1]
                p_new = (p_old[7:11]) + (p_old[0:6])
            #get n
            if not n_new and line.startswith('N '):
                pieces = line.split()
                n_old = pieces[1]                        
                n_new = (n_old[0:15]) + "/" + (n_old[18:20])
            if p_new and n_new:
                break
    list_parsed_items.append([p_new, n_new])

Upvotes: 2

Related Questions