4

I want to pad a number i with a padding based on the value of the variable width

>>> width = 5
>>> i = 1
>>> print(f'{i:width}')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid format specifier
>>>
>>> print('{:width}'.format(i))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid format specifier

Desired output:

1
ruohola
  • 21,987
  • 6
  • 62
  • 97
Abhishek Bhatia
  • 547
  • 4
  • 11
  • [Parametrized formats](https://pyformat.info/#param_align) – Tomerikoo Aug 18 '19 at 17:54
  • @Tomerikoo do you know of any updated versions of that covering f-strings? – Karl Knechtel Jul 13 '22 at 13:38
  • @KarlKnechtel Not specifically, but I believe it mostly covers it (assuming some very basic understanding of the syntaxes). Anyway, it is possible to contribute to that site [through GitHub](https://github.com/ulope/pyformat.info) apparently – Tomerikoo Jul 13 '22 at 13:44

1 Answers1

3

You almost had it:

>>> width = 5
>>> i = 1
>>> print(f'{i:{width}}')
    1
ruohola
  • 21,987
  • 6
  • 62
  • 97