Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I dynamically pad a number in python f-strings?

I have an f-string like this:

f"foo-{i:03d}"

This is producing a filename for a file that I read in. The problem is sometimes there are hundreds of files, so the files are named like foo-001, foo-002, etc., but other times there are thousands, so the files are foo-0001 and 04d would be needed. Is there a way I can do this dynamically? For example, if I have the total number of files as a variable n, then I could do:

pad = len(str(n))

but then how do I use that pad variable in the f-string?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Nested f-string:

>>> pad = 4
>>> i = 1
>>> f"foo-{i:>0{pad}}"
'foo-0001'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading