Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a range of numbers as strings Python

Tags:

python

loops

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

like image 863
Moohan Avatar asked Nov 03 '17 10:11

Moohan


People also ask

Can you use range for strings Python?

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.

How do you make a string of numbers in Python?

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.

How do you create a range of numbers in a list in Python?

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.

How do I turn a list into a string in Python?

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.


1 Answers

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
>>> 
like image 60
Sandeep Lade Avatar answered Oct 08 '22 01:10

Sandeep Lade