tags:

views:

649

answers:

6

Hello,

Does anyone knows what magic I have to use to change x list:

x = [1,2,3,4,5,11]

into y list?

y = ['01','02','03','04','05','11']

Thank you all in advance for helping me...

+6  A: 

You want to use the built-in map function:

>>> x = [1,2,3,4,5]
>>> x
[1, 2, 3, 4, 5]
>>> y = map(str, x)
>>> y
['1', '2', '3', '4', '5']

EDIT You changed the requirements on me! To make it display leading zeros, you do this:

>>> x = [1,2,3,4,5,11]
>>> y = ["%02d" % v for v in x]
>>> y
['01', '02', '03', '04', '05', '11']
Paolo Bergantino
that semi-colon is staring at me! stop it!
jcoon
Whooops! Old habits die hard.
Paolo Bergantino
And if I'd like to add zero if the number is one digit and I want my numbers to be 2 digit each?
I updated my answer to show how to display the leading zero.
Paolo Bergantino
Thank you Paolo!
+15  A: 

You can use a list comprehension (Python 2.6+):

y = ["{0:0>2}".format(v) for v in x]

Or for Python prior to 2.6:

y = ["%02d" % v for v in x]

Edit: Missed the fact that you wanted zero-padding...

DNS
Interesting, I haven't heard of this "{0:0>2}" syntax. Is it covered on any PEP or other document?
Rodrigo
It's a new syntax that's (supposedly) meant to gradually replace % syntax. It's actually very nice for some things, and I've made a point of using it in my code, but it still looks weird to me after so long using %. More info here: http://docs.python.org/library/string.html#formatstrings
DNS
A: 

to get the 0's:

y = ['%02d' % i for i in x]
jcoon
A: 
y = ['%02d'%v for v in x]
Angela
+2  A: 

I would use a list comprehension myself, but here is another solution using map for those interested...

map(lambda v: "%02d" %v, x)
Brian R. Bondy
A: 

An alternative to format strings would be to use the string's zfill() method:

y = [str(i).zfill(2) for i in x]

Another thing: you might be after padding based on the largest item in the list, so instead of just using 2, you could do:

pad_length = len(str(max(x)))
y = [str(i).zfill(pad_length) for i in x]