Search code examples
pythonf-string

How to restrict the number of digits in an fstring in Python


I would like to use an f-string in Python to generate the following folders:

folder01
folder02
folder03
folder04
folder05
folder06
folder07
folder08
folder09
folder10
folder11

I currently have the following code, which obviously doesn't do what I want, but how can I change it so that it does?

folders = [f"folder0{i}" for i in range(0,12)]

This generates:

folder01
folder02
folder03
folder04
folder05
folder06
folder07
folder08
folder09
folder010
folder011

Notice the extra 0 with folder010 and folder011


Solution

  • You can do that in simple way

    folders = [f"Folder{i:0=2d}" for i in range(1,12)]
    
    print(folders)
    

    Output

    ['Folder01', 'Folder02', 'Folder03', 'Folder04', 'Folder05', 'Folder06', 'Folder07', 'Folder08', 'Folder09', 'Folder10', 'Folder11']