1

Is there a way to assign the output from a for loop as variables for the output from a method? Both outputs will be lists of the same length.

Below, I am performing the .pages method in pdfplumber on each page of a pdf. I want to assign each page to a variable p0, p1, p2... etc, then extract the text using the .extracttext method. The total number of pages will be dynamic so I can't simply unpack the list as (p1, p2, p3) = .....

I am printing just to provide an output for visual aid.

import pdfplumber

with pdfplumber.open(file) as pdf:
    
    print(pdf.pages)
        
    for pages in total_pages_range:
        print("p" + str(pages))

The outputs are:

[<pdfplumber.page.Page object at 0x7ff6b75e9c50>, <pdfplumber.page.Page object at 0x7ff6b761a4d0>]
p0
p1

I need p0 = <pdfplumber.page.Page object at 0x7ff6b75e9c50> and p1 = <pdfplumber.page.Page object at 0x7ff6b761a4d0>. But with the capability for p2 = ....., p3 = ...... etc. Could a dictionary be used here?

Many thanks, G

Guy Buckle
  • 27
  • 6
  • Don't set variables. Just use a dictionary, or a list. Dynamic variables are rarely worth your time, because then you also have to write code elsewhere to read those dynamic variables again. – Martijn Pieters Aug 13 '20 at 10:28

1 Answers1

5

If I understand your request correctly, use dict comprehension:

pages_map = {f'p{i}': page for i, page in enumerate(pdf.pages)}
Or Y
  • 2,088
  • 3
  • 16