Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 765
KevinShaffer Avatar asked Jul 10 '13 18:07

KevinShaffer


People also ask

How do you convert a range to a string in Python?

We can convert numbers to strings using the str() method. We'll pass either a number or a variable into the parentheses of the method and then that numeric value will be converted into a string value.

What is the output of list Range 10 ))?

range(10) returns an object that prints as range(0, 10) (since it shows the starting value when it prints) and whose elements are the integers from 0 to 9, so [range(10)] gives the one-element list [range(0, 10)] and list(range(10)) gives the 10-element list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] .


1 Answers

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']
like image 111
Ashwini Chaudhary Avatar answered Sep 29 '22 00:09

Ashwini Chaudhary