How to left pad a number with zeros in jinja2

Viewed 5908

How can I output an integer in jinja2 as a string with a leading zero? So a variable containing 4 (integer) becomes "04"?

1 Answers

You can use the following to zero-pad numeric strings to be at least 2 characters long:

{{ '%02d' % your_variable }}

Some examples of input and output:

9   --> 09
10  --> 10
123 --> 123
x   --> TypeError: %d format: a number is required, not str

Changing the 2 yields the results you would expect and things get a little more interesting when you make room for decimals. Using '%05d' gives the following results:

9      --> 00009
10     --> 00010
123    --> 00123
123456 --> 123456
34.2   --> 00034
34.8   --> 00034

Thanks to askaroni's comment for pointing me in the right direction

Related