Convert range(r) to list of strings of length 2 in python
Asked Answered
M

6

14

I just want to change a list (that I make using range(r)) to a list of strings, but if the length of the string is 1, tack a 0 on the front. I know how to turn the list into strings using

ranger= map(str,range(r))

but I want to be able to also change the length of those strings.

Input:

r = 12
ranger = range(r)
ranger = magic_function(ranger)

Output:

print ranger
>>> ['00','01','02','03','04','05','06','07','08','09','10','11']

And if possible, my final goal is this: I have a matrix of the form

numpy.array([[1,2,3],[4,5,6],[7,8,9]])

and I want to make a set of strings such that the first 2 characters are the row, the second two are the column and the third two are '01', and have matrix[row,col] of each one of these. so the above values would look like such:

000001    since matrix[0,0] = 1
000101    since matrix[0,1] = 2
000101    since matrix[0,1] = 2
000201
000201
000201
etc
Maledict answered 10/7, 2013 at 18:5 Comment(0)
B
27

Use string formatting and list comprehension:

>>> lst = range(11)
>>> ["{:02d}".format(x) for x in lst]
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10']

or format:

>>> [format(x, '02d') for x in lst]
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10']
Billman answered 10/7, 2013 at 18:7 Comment(1)
Great use of the format() built-in function with the 2nd exampleEureka
I
16

zfill does exactly what you want and doesn't require you to understand an arcane mini-language as with the various types of string formatting. There's a place for that, but this is a simple job with a ready-made built-in tool.

ranger = [str(x).zfill(2) for x in range(r)]
Isleen answered 10/7, 2013 at 18:40 Comment(0)
T
6

Here's my take on it:

>>> map('{:02}'.format, xrange(12))
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11']

For your own enlightenment, try reading about the format string syntax.

Timberlake answered 10/7, 2013 at 18:9 Comment(1)
does this return a map object?Succession
N
3

Use string formatting:

>>> sr = []
>>> for r in range(11):
...     sr.append('%02i' % r)
... 
>>> sr
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10']
Nussbaum answered 10/7, 2013 at 18:9 Comment(0)
C
1

One liner in Python 3.x

>>> ranger =  [f'{i:>02}' for i in range(1, 12)]
>>> print (ranger)

['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11']
Cyanohydrin answered 2/9, 2022 at 17:8 Comment(0)
G
0

As in Ashwini Chaudhary's solution, you can use range() within list comprehension:

code:

my_list = [format(x, '02d') for x in range(11)]
print(my_list)

output: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10']

Guesswork answered 12/1 at 0:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.