-2

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'
  • Please [edit] your post to include the full error and it's traceback – mousetail May 01 '23 at 11:47
  • 4
    `f'... {i:03}'`… – deceze May 01 '23 at 11:48
  • This seems to be a good question, and not a duplicate. Padding integers with zeros is different from padding strings with spaces, and uses different f-string identifiers to do so. The correct answer (imo) of `f"The value is {i:03d}."` has not been posted here, and would not be posted in the "duplicate" string-related question. – mightypile Jul 17 '23 at 21:29

1 Answers1

0

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)
warped
  • 8,947
  • 3
  • 22
  • 49