16

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...

4 Answers 4

23

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'
Sign up to request clarification or add additional context in comments.

Comments

8
>>> [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']

Comments

4

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
>>> 

1 Comment

In Python 2.7 the formatting method for string objects is already supported. So you can be compatible with Python 3.x by doing this: ["{:02}".format(n) for n in range(17)]
1

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.