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...
range() function only works with the integers, i.e. whole numbers. All arguments must be integers. Users can not pass a string or float number or any other type in a start, stop and step argument of a range(). All three arguments can be positive or negative.
In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string.
To convert a Python Range to Python List, use list() constructor, with range object passed as argument. list() constructor returns a list generated using the range. Or you can use a for loop to append each item of range to list.
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
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
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With