40

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...

7 Answers 7

54

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]

Or for Python 3.6+ using f-strings:

y = [f'{v:02}' for v in x] 

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

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting, I haven't heard of this "{0:0>2}" syntax. Is it covered on any PEP or other document?
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: docs.python.org/library/string.html#formatstrings
23

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'] 

3 Comments

that semi-colon is staring at me! stop it!
Whooops! Old habits die hard.
And if I'd like to add zero if the number is one digit and I want my numbers to be 2 digit each?
10

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

map(lambda v: "%02d" %v, x)

Comments

1
y = ['%02d'%v for v in x]

Comments

1

Try this:

>>> [str(v).rjust(2,'0') for v in x]
['01', '02', '03', '04', '05', '11']

rjust as a method of string class, takes an integer argument(result length) and an optional padding character

Comments

0

to get the 0's:

y = ['%02d' % i for i in x]

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.