Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display number with leading zeros

Given:

a = 1 b = 10 c = 100 

How do I display a leading zero for all numbers with less than two digits?

This is the output I'm expecting:

01 10 100 
like image 574
ashchristopher Avatar asked Sep 25 '08 18:09

ashchristopher


People also ask

How do you display leading zeros?

Use the "0"# format when you want to display one leading zero. When you use this format, the numbers that you type and the numbers that Microsoft Excel displays are listed in the following table. Example 2: Use the "000"# format when you want to display three leading zeros.

How do you pad a number with leading zeros?

To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.


Video Answer


1 Answers

In Python 2 (and Python 3) you can do:

number = 1 print("%02d" % (number,)) 

Basically % is like printf or sprintf (see docs).


For Python 3.+, the same behavior can also be achieved with format:

number = 1 print("{:02d}".format(number)) 

For Python 3.6+ the same behavior can be achieved with f-strings:

number = 1 print(f"{number:02d}") 
like image 148
Jack M. Avatar answered Sep 26 '22 22:09

Jack M.