Moohan
Moohan

Reputation: 1011

Generating a range of numbers as strings Python

I need to loop over a number of files with structured files names.

They are of the form 'Mar00.sav', 'Sep00.sav', 'Mar01.sav'

At the moment I do this;

Years = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17']

Which works but I was wondering if there is a better way?

I tried range but str(range(00,17)) will drop the leading zeros...

Upvotes: 16

Views: 45461

Answers (4)

Ali
Ali

Reputation: 500

In Python 3 you can use f string:

>>>[f"{i:02d}" for i in range(0,17)]
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16']

Upvotes: 1

Satheesh Alathiyur
Satheesh Alathiyur

Reputation: 111

>>> [str(i).zfill(2) for i in range(1,18)]
['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17']

Upvotes: 8

Sandeep Lade
Sandeep Lade

Reputation: 1943

In python 2.7 , you can achieve it like this

>>> ["%02d" %i for i in range(0,17)]
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16']
>>> 

if you want to print

>>> for i in range(00,17):
        print '%02d' %i


00
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
>>> 

Upvotes: 4

taras
taras

Reputation: 3705

I had the same issue and there is a perfect solution to it -zfill method

An example of usage:

>>> str('1').zfill(7)
'0000001'

What you need to do is to create a generator for N numbers and fill its string representation with zeros.

>>> for i in range(1, 18):
...     str(i).zfill(2)
...
'01'
'02'
'03'
...
'16'
'17'

Upvotes: 23

Related Questions