Skip to content

Python range to the list of strings | Example code

  • by

Need to loop over a number of files with structured files names. They are of the form ‘Mar00.sav’, ‘Sep00.sav’, ‘Mar01.sav’

Example code of range to the list of strings in Python

Python simple example code.

There is a perfect solution to it -zfill method. Generator for N numbers and fill its string representation with zeros.

list1 = []
for i in range(1, 7):
    list1.append(str(i).zfill(2))

print(list1)

Output:

Python range to the list of strings

Use string formatting and list comprehension:

lst = range(11)

print(["{:02d}".format(x) for x in lst])

Output:

[’00’, ’01’, ’02’, ’03’, ’04’, ’05’, ’06’, ’07’, ’08’, ’09’, ’10’]

or format:

lst = range(11)

print([format(x, '02d') for x in lst])

Output:

[’00’, ’01’, ’02’, ’03’, ’04’, ’05’, ’06’, ’07’, ’08’, ’09’, ’10’]

Use string formatting:

sr = []
for r in range(11):
    sr.append('%02i' % r)

print(sr)

Do comment if you have any doubts and suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading