Skip to content

Commit 0ea8901

Browse files
committed
Replace most %-strings with f-strings.
Fix syntax error, move dict because copilot nitpick. Use sql parameterization. Some loops inserted where repeated logic was used.
1 parent 13f133f commit 0ea8901

18 files changed

+246
-302
lines changed

docs/app4.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,7 @@ These are the :title:`Python` commands for how each tool is used:
374374
doc=pymupdf.open(datei)
375375
for p in pymupdf.Pages(doc):
376376
pix = p.get_pixmap(dpi=150)
377-
pix.save("t-%s.png" % p.number)
377+
pix.save(f"t-{p.number}.png")
378378
pix = None
379379
doc.close()
380380
return

docs/document.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ For details on **embedded files** refer to Appendix 3.
228228

229229
>>> import pymupdf
230230
>>> with pymupdf.open(...) as doc:
231-
for page in doc: print("page %i" % page.number)
231+
for page in doc: print(f"page {page.number}")
232232
page 0
233233
page 1
234234
page 2
@@ -2254,10 +2254,10 @@ Other Examples
22542254
xref = img[0] # xref number
22552255
pix = pymupdf.Pixmap(doc, xref) # make pixmap from image
22562256
if pix.n - pix.alpha < 4: # can be saved as PNG
2257-
pix.save("p%s-%s.png" % (i, xref))
2257+
pix.save(f"p{i}-{xref}.png")
22582258
else: # CMYK: must convert first
22592259
pix0 = pymupdf.Pixmap(pymupdf.csRGB, pix)
2260-
pix0.save("p%s-%s.png" % (i, xref))
2260+
pix0.save(f"p{i}-{xref}.png")
22612261
pix0 = None # free Pixmap resources
22622262
pix = None # free Pixmap resources
22632263

docs/font.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ A ``Font`` object also contains useful general information, like the font bbox,
158158
>>> font = pymupdf.Font("math")
159159
>>> vuc = font.valid_codepoints()
160160
>>> for i in vuc:
161-
print("%04X %s (%s)" % (i, chr(i), font.unicode_to_glyph_name(i)))
161+
>>> print(f"{i:04X} {chr(i)} ({font.unicode_to_glyph_name(i)})")
162162
0000
163163
000D (CR)
164164
0020 (space)

docs/functions.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -763,7 +763,7 @@ Yet others are handy, general-purpose utilities.
763763
try:
764764
return sum([widthlist[ord(c)] for c in text]) * fontsize
765765
except IndexError:
766-
raise ValueError:("max. code point found: %i, increase limit" % ord(max(text)))
766+
raise ValueError(f"max. code point found: {ord(max(text))}, increase limit")
767767

768768
-----
769769

docs/recipes-common-issues-and-their-solutions.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ It features maintaining any metadata, table of contents and links contained in t
8686
raise SystemExit("need PyMuPDF v1.14.0+")
8787
fn = sys.argv[1]
8888

89-
print("Converting '%s' to '%s.pdf'" % (fn, fn))
89+
print(f"Converting '{fn}' to '{fn}.pdf'")
9090

9191
doc = pymupdf.open(fn)
9292

@@ -123,7 +123,7 @@ It features maintaining any metadata, table of contents and links contained in t
123123
pdf.save(fn + ".pdf", garbage=4, deflate=True)
124124
# say how many named links we skipped
125125
if link_cnti > 0:
126-
print("Skipped %i named links of a total of %i in input." % (link_skip, link_cnti))
126+
print(f"Skipped {link_skip} named links of a total of {link_cnti} in input.")
127127

128128

129129

docs/recipes-images.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ The script works as a command line tool which expects the filename being supplie
2424
doc = pymupdf.open(fname) # open document
2525
for page in doc: # iterate through the pages
2626
pix = page.get_pixmap() # render page to an image
27-
pix.save("page-%i.png" % page.number) # store image as a PNG
27+
pix.save(f"page-{page.number}.png") # store image as a PNG
2828

2929
The script directory will now contain PNG image files named *page-0.png*, *page-1.png*, etc. Pictures have the dimension of their pages with width and height rounded to integers, e.g. 595 x 842 pixels for an A4 portrait sized page. They will have a resolution of 96 dpi in x and y dimension and have no transparency. You can change all that -- for how to do this, read the next sections.
3030

@@ -525,8 +525,8 @@ This script creates an approximate image of it as a PNG, by going down to one-pi
525525
t1 = time.perf_counter()
526526
pm.save("sierpinski-punch.png")
527527
t2 = time.perf_counter()
528-
print ("%g sec to create / fill the pixmap" % round(t1-t0,3))
529-
print ("%g sec to save the image" % round(t2-t1,3))
528+
print (f"{round(t1-t0,3)} sec to create / fill the pixmap")
529+
print (f"{round(t2-t1,3)} sec to save the image")
530530

531531
The result should look something like this:
532532

docs/recipes-journalling.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,8 @@ Description:
109109
>>> page=doc.new_page()
110110
>>> doc.journal_stop_op()
111111
>>> for i in range(5):
112-
doc.journal_start_op("insert-%i" % i)
113-
page.insert_text((100, 100 + 20*i), "text line %i" %i)
112+
doc.journal_start_op(f"insert-{i}")
113+
page.insert_text((100, 100 + 20*i), f"text line {i}")
114114
doc.journal_stop_op()
115115

116116
>>> # combined status info:

docs/recipes-low-level-interfaces.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ The following script loops through the :data:`xref` table and prints each object
2323
>>> xreflen = doc.xref_length() # length of objects table
2424
>>> for xref in range(1, xreflen): # skip item 0!
2525
print("")
26-
print("object %i (stream: %s)" % (xref, doc.xref_is_stream(xref)))
26+
print(f"object {xref} (stream: {doc.xref_is_stream(xref)})")
2727
print(doc.xref_object(xref, compressed=False))
2828

2929

@@ -324,7 +324,7 @@ There also exist granular, elegant ways to access and manipulate selected PDF :d
324324
* Here is a full listing of the above page keys::
325325

326326
In [9]: for key in doc.xref_get_keys(page.xref):
327-
...: print("%s = %s" % (key, doc.xref_get_key(page.xref, key)))
327+
...: print(f"{key} = {doc.xref_get_key(page.xref, key)}")
328328
...:
329329
Type = ('name', '/Page')
330330
Contents = ('xref', '1297 0 R')

docs/recipes-text.rst

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,12 +93,11 @@ This is the responsibility of the PDF creator (software or a human). For example
9393

9494
doc = pymupdf.open("some.pdf")
9595
header = "Header" # text in header
96-
footer = "Page %i of %i" # text in footer
9796
for page in doc:
9897
page.insert_text((50, 50), header) # insert header
9998
page.insert_text( # insert footer 50 points above page bottom
10099
(50, page.rect.height - 50),
101-
footer % (page.number + 1, doc.page_count),
100+
f"Page {page.number + 1} of {doc.page_count}", # text in footer
102101
)
103102

104103
The text sequence extracted from a page modified in this way will look like this:
@@ -166,15 +165,15 @@ But you also have other options::
166165
text = sys.argv[2] # search string
167166
doc = pymupdf.open(fname)
168167

169-
print("underlining words containing '%s' in document '%s'" % (word, doc.name))
168+
print(f"underlining words containing '{word}' in document '{doc.name}'")
170169

171170
new_doc = False # indicator if anything found at all
172171

173172
for page in doc: # scan through the pages
174173
found = mark_word(page, text) # mark the page's words
175174
if found: # if anything found ...
176175
new_doc = True
177-
print("found '%s' %i times on page %i" % (text, found, page.number + 1))
176+
print(f"found '{text}' {found} times on page {page.number + 1}")
178177

179178
if new_doc:
180179
doc.save("marked-" + doc.name)
@@ -329,7 +328,7 @@ Output some text lines on a page::
329328
fontsize = 11, # the default font size
330329
rotate = 0, # also available: 90, 180, 270
331330
)
332-
print("%i lines printed on page %i." % (rc, page.number))
331+
print(f"{rc} lines printed on page {page.number}.")
333332

334333
doc.save("text.pdf")
335334

docs/samples/filmfestival-sql.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,7 @@
6868
select_films = """SELECT title, director, year FROM films ORDER BY title"""
6969

7070
# select stament for actors, a skeleton: sub-select by film title
71-
select_casts = """SELECT name FROM actors WHERE film = "%s" ORDER BY name"""
72-
71+
select_casts = """SELECT name FROM actors WHERE film = ? ORDER BY name"""
7372
# -------------------------------------------------------------------
7473
# define the HTML Story and fill it with database data
7574
# -------------------------------------------------------------------
@@ -89,7 +88,7 @@
8988
film.find(None, "id", "filmyear").add_text(str(year)) # put year
9089

9190
# the actors reside in their own table - find the ones for this film title
92-
cursor_casts.execute(select_casts % title) # execute cursor
91+
cursor_casts.execute(select_casts, (title,)) # execute cursor
9392
casts = cursor_casts.fetchall() # read actors for the film
9493
# each actor name appears in its own tuple, so extract it from there
9594
film.find(None, "id", "cast").add_text("\n".join([c[0] for c in casts]))

0 commit comments

Comments
 (0)