Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pad numbers with variable substitution for padding width in format or f string? [duplicate]

Tags:

python

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
like image 669
Abhishek Bhatia Avatar asked Oct 18 '25 17:10

Abhishek Bhatia


1 Answers

You almost had it:

>>> width = 5
>>> i = 1
>>> print(f'{i:{width}}')
    1
like image 118
ruohola Avatar answered Oct 20 '25 08:10

ruohola