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

Time:04-09

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?

CodePudding user response:

Nested f-string:

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

CodePudding user response:

Instead of using an f-string, str.zfill() may be preferable:

"foo-"   str(i).zfill( len(str(n)) )

Advantages:

  • Cleaner syntax
  • Available in older Python versions
  • Related