Categories
Uncategorized

Formatting Integers – Python

We have a range from 1 to 100 and we want to format the integers so that they look nice. Something like this

001
002
003
004
005
...
010
011
012
...
098
099
100

so first we create the range

list_ints = range(1,101)

which should result in something like this

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 
 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 
 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 
 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 
 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]

The actual formatting code is quite simple, this

'%0*d'%(3,int_one)

But to apply it to a list, we can do this

list_ints = ['%0*d'%(3,x) for x in list_ints]

where '%0*d' means that the digit will be preceded by zeros if it is not 3 digits long. This can be changed to any other digit, symbol or space. Then x stands for each value and the 3 is the total length of the number.

This will result in a list of strings that looks like this

['001', '002', '003', '004', '005', '006', '007', '008', '009', '010',
 '011', '012', '013', '014', '015', '016', '017', '018', '019', '020',
 '021', '022', '023', '024', '025', '026', '027', '028', '029', '030',
 '031', '032', '033', '034', '035', '036', '037', '038', '039', '040',
 '041', '042', '043', '044', '045', '046', '047', '048', '049', '050',
 '051', '052', '053', '054', '055', '056', '057', '058', '059', '060',
 '061', '062', '063', '064', '065', '066', '067', '068', '069', '070', 
 '071', '072', '073', '074', '075', '076', '077', '078', '079', '080',
 '081', '082', '083', '084', '085', '086', '087', '088', '089', '090',
 '091', '092', '093', '094', '095', '096', '097', '098', '099', '100']

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s