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
JavaScript
x
2
1
ranger= map(str,range(r))
2
but I want to be able to also change the length of those strings.
Input:
JavaScript
1
4
1
r = 12
2
ranger = range(r)
3
ranger = magic_function(ranger)
4
Output:
JavaScript
1
3
1
print ranger
2
>>> ['00','01','02','03','04','05','06','07','08','09','10','11']
3
And if possible, my final goal is this: I have a matrix of the form
JavaScript
1
2
1
numpy.array([[1,2,3],[4,5,6],[7,8,9]])
2
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:
JavaScript
1
8
1
000001 since matrix[0,0] = 1
2
000101 since matrix[0,1] = 2
3
000101 since matrix[0,1] = 2
4
000201
5
000201
6
000201
7
etc
8
Advertisement
Answer
Use string formatting
and list comprehension:
JavaScript
1
4
1
>>> lst = range(11)
2
>>> ["{:02d}".format(x) for x in lst]
3
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10']
4
or format
:
JavaScript
1
3
1
>>> [format(x, '02d') for x in lst]
2
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10']
3