How to zero pad an f-string?

3.4k Views Asked by At

Like this is how you can 0 pad a format string

for i in range(10):
   zeropad = "Value is{:03}.".format(i)
   print(zeropad)

and you get result as

Value is 000
Value is 001

and so on...

So, how can i do the same thing with f-strings??

I tried using the .zfill() function, but that doesnt work either

for i in range(1, 11):
  sentence = f"The value is {i(zfill(3))}."
  print(sentence)`

This gives an error

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    sentence = f"The value is {i.zfill(3)}."
AttributeError: 'int' object has no attribute 'zfill'
1

There are 1 best solutions below

2
warped On

fix for your approach:

for i in range(1, 11):
    sentence = f"The value is {str(i).zfill(3)}."
    print(sentence)
    

f-string approach

for i in range(1, 11):
    sentence = f"The value is {i:03}."
    print(sentence)