Skip to content

Cleanup string formatting. #4587

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/app4.rst
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ These are the :title:`Python` commands for how each tool is used:
doc=pymupdf.open(datei)
for p in pymupdf.Pages(doc):
pix = p.get_pixmap(dpi=150)
pix.save("t-%s.png" % p.number)
pix.save(f"t-{p.number}.png")
pix = None
doc.close()
return
Expand Down
6 changes: 3 additions & 3 deletions docs/document.rst
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ For details on **embedded files** refer to Appendix 3.

>>> import pymupdf
>>> with pymupdf.open(...) as doc:
for page in doc: print("page %i" % page.number)
for page in doc: print(f"page {page.number}")
page 0
page 1
page 2
Expand Down Expand Up @@ -2254,10 +2254,10 @@ Other Examples
xref = img[0] # xref number
pix = pymupdf.Pixmap(doc, xref) # make pixmap from image
if pix.n - pix.alpha < 4: # can be saved as PNG
pix.save("p%s-%s.png" % (i, xref))
pix.save(f"p{i}-{xref}.png")
else: # CMYK: must convert first
pix0 = pymupdf.Pixmap(pymupdf.csRGB, pix)
pix0.save("p%s-%s.png" % (i, xref))
pix0.save(f"p{i}-{xref}.png")
pix0 = None # free Pixmap resources
pix = None # free Pixmap resources

Expand Down
2 changes: 1 addition & 1 deletion docs/font.rst
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ A ``Font`` object also contains useful general information, like the font bbox,
>>> font = pymupdf.Font("math")
>>> vuc = font.valid_codepoints()
>>> for i in vuc:
print("%04X %s (%s)" % (i, chr(i), font.unicode_to_glyph_name(i)))
>>> print(f"{i:04X} {chr(i)} ({font.unicode_to_glyph_name(i)})")
0000
000D (CR)
0020 (space)
Expand Down
2 changes: 1 addition & 1 deletion docs/functions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -763,7 +763,7 @@ Yet others are handy, general-purpose utilities.
try:
return sum([widthlist[ord(c)] for c in text]) * fontsize
except IndexError:
raise ValueError:("max. code point found: %i, increase limit" % ord(max(text)))
raise ValueError(f"max. code point found: {ord(max(text))}, increase limit")

-----

Expand Down
4 changes: 2 additions & 2 deletions docs/recipes-common-issues-and-their-solutions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ It features maintaining any metadata, table of contents and links contained in t
raise SystemExit("need PyMuPDF v1.14.0+")
fn = sys.argv[1]

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

doc = pymupdf.open(fn)

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



Expand Down
6 changes: 3 additions & 3 deletions docs/recipes-images.rst
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ The script works as a command line tool which expects the filename being supplie
doc = pymupdf.open(fname) # open document
for page in doc: # iterate through the pages
pix = page.get_pixmap() # render page to an image
pix.save("page-%i.png" % page.number) # store image as a PNG
pix.save(f"page-{page.number}.png") # store image as a PNG

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.

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

The result should look something like this:

Expand Down
4 changes: 2 additions & 2 deletions docs/recipes-journalling.rst
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,8 @@ Description:
>>> page=doc.new_page()
>>> doc.journal_stop_op()
>>> for i in range(5):
doc.journal_start_op("insert-%i" % i)
page.insert_text((100, 100 + 20*i), "text line %i" %i)
doc.journal_start_op(f"insert-{i}")
page.insert_text((100, 100 + 20*i), f"text line {i}")
doc.journal_stop_op()

>>> # combined status info:
Expand Down
4 changes: 2 additions & 2 deletions docs/recipes-low-level-interfaces.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ The following script loops through the :data:`xref` table and prints each object
>>> xreflen = doc.xref_length() # length of objects table
>>> for xref in range(1, xreflen): # skip item 0!
print("")
print("object %i (stream: %s)" % (xref, doc.xref_is_stream(xref)))
print(f"object {xref} (stream: {doc.xref_is_stream(xref)})")
print(doc.xref_object(xref, compressed=False))


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

In [9]: for key in doc.xref_get_keys(page.xref):
...: print("%s = %s" % (key, doc.xref_get_key(page.xref, key)))
...: print(f"{key} = {doc.xref_get_key(page.xref, key)}")
...:
Type = ('name', '/Page')
Contents = ('xref', '1297 0 R')
Expand Down
9 changes: 4 additions & 5 deletions docs/recipes-text.rst
Original file line number Diff line number Diff line change
Expand Up @@ -93,12 +93,11 @@ This is the responsibility of the PDF creator (software or a human). For example

doc = pymupdf.open("some.pdf")
header = "Header" # text in header
footer = "Page %i of %i" # text in footer
for page in doc:
page.insert_text((50, 50), header) # insert header
page.insert_text( # insert footer 50 points above page bottom
(50, page.rect.height - 50),
footer % (page.number + 1, doc.page_count),
f"Page {page.number + 1} of {doc.page_count}", # text in footer
)

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

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

new_doc = False # indicator if anything found at all

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

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

doc.save("text.pdf")

Expand Down
5 changes: 2 additions & 3 deletions docs/samples/filmfestival-sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@
select_films = """SELECT title, director, year FROM films ORDER BY title"""

# select stament for actors, a skeleton: sub-select by film title
select_casts = """SELECT name FROM actors WHERE film = "%s" ORDER BY name"""

select_casts = """SELECT name FROM actors WHERE film = ? ORDER BY name"""
# -------------------------------------------------------------------
# define the HTML Story and fill it with database data
# -------------------------------------------------------------------
Expand All @@ -89,7 +88,7 @@
film.find(None, "id", "filmyear").add_text(str(year)) # put year

# the actors reside in their own table - find the ones for this film title
cursor_casts.execute(select_casts % title) # execute cursor
cursor_casts.execute(select_casts, (title,)) # execute cursor
casts = cursor_casts.fetchall() # read actors for the film
# each actor name appears in its own tuple, so extract it from there
film.find(None, "id", "cast").add_text("\n".join([c[0] for c in casts]))
Expand Down
6 changes: 3 additions & 3 deletions docs/samples/multiprocess-render.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def render_page(vector):
pix = page.get_pixmap(alpha=False, matrix=mat)
# store away the result somewhere ...
# pix.save("p-%i.png" % i)
print("Processed page numbers %i through %i" % (seg_from, seg_to - 1))
print(f"Processed page numbers {seg_from} through {seg_to - 1}")


if __name__ == "__main__":
Expand All @@ -69,10 +69,10 @@ def render_page(vector):

# make vectors of arguments for the processes
vectors = [(i, cpu, filename, mat) for i in range(cpu)]
print("Starting %i processes for '%s'." % (cpu, filename))
print(f"Starting {cpu} processes for '{filename}'.")

pool = Pool() # make pool of 'cpu_count()' processes
pool.map(render_page, vectors, 1) # start processes passing each a vector

t1 = mytime() # stop the timer
print("Total time %g seconds" % round(t1 - t0, 2))
print(f"Total time {round(t1 - t0, 2):g} seconds")
5 changes: 2 additions & 3 deletions docs/samples/new-annots.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@
def print_descr(annot):
"""Print a short description to the right of each annot rect."""
annot.parent.insert_text(
annot.rect.br + (10, -5), "%s annotation" % annot.type[1], color=red
)
annot.rect.br + (10, -5), f"{annot.type[1]} annotation", color=red)


doc = pymupdf.open()
Expand Down Expand Up @@ -166,4 +165,4 @@ def print_descr(annot):
annot = page.add_redact_annot(r)
print_descr(annot)

doc.save(__file__.replace(".py", "-%i.pdf" % page.rotation), deflate=True)
doc.save(__file__.replace(".py", f"-{page.rotation:d}.pdf"), deflate=True)
14 changes: 6 additions & 8 deletions docs/samples/text-lister.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,9 @@ def flags_decomposer(flags):
for l in b["lines"]: # iterate through the text lines
for s in l["spans"]: # iterate through the text spans
print("")
font_properties = "Font: '%s' (%s), size %g, color #%06x" % (
s["font"], # font name
flags_decomposer(s["flags"]), # readable font flags
s["size"], # font size
s["color"], # font color
)
print("Text: '%s'" % s["text"]) # simple print of text
print(font_properties)
s_font = s['font']
s_flags = flags_decomposer(s['flags'])
s_size = s['size']
s_color = s['color']
print(f"Text: '{s['text']}'") # simple print of text
print(f"Font: '{s_font}' ({s_flags}), size {s_size}, color #{s_color:06x}")
2 changes: 1 addition & 1 deletion docs/the-basics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ To extract all the images from a |PDF| file, do the following:
if pix.n - pix.alpha > 3: # CMYK: convert to RGB first
pix = pymupdf.Pixmap(pymupdf.csRGB, pix)

pix.save("page_%s-image_%s.png" % (page_index, image_index)) # save the image as png
pix.save(f"page_{page_index}-image_{image_index}.png") # save the image as png
pix = None


Expand Down
2 changes: 1 addition & 1 deletion docs/tutorial.rst
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ Saving the Page Image in a File
-----------------------------------
We can simply store the image in a PNG file::

pix.save("page-%i.png" % page.number)
pix.save(f"page-{page.number}.png")

Displaying the Image in GUIs
-------------------------------------------
Expand Down
Loading