Search code examples
pythonf-string

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?


Solution

  • Nested f-string:

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