Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to left pad a number with zeros in jinja2

Tags:

jinja2

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

like image 372
Sam Avatar asked Oct 04 '19 08:10

Sam


People also ask

How can I pad an integer with zeros on the left?

format("%05d", yournumber); for zero-padding with a length of 5.

How can I pad an integer with zeros on the left Python?

Use str. zfill(width) zfill is the best method to pad zeros from the left side as it can also handle a leading '+' or '-' sign. It returns a copy of the string left filled with '0' digits to make a string of length width.

How do you remove zeros at the beginning of a number in Python?

Use the lstrip() Function Along With List Comprehension to Remove Leading Zeros in a String in Python. The lstrip() can be utilized to remove the leading characters of the string if they exist. By default, a space is the leading character to remove in the string.


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

like image 127
Sam Avatar answered Sep 22 '22 03:09

Sam