2

i have a list like this :

a=[1000,200,30]

and i want to get a list like this :

['01000','00200','00030']

so what can i do ,

thanks

5 Answers 5

8
>>> a=[1000,200,30]
>>> [str(e).zfill(5) for e in a]
['01000', '00200', '00030']

str.zfill

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

1 Comment

I thought that might choke on -30 but no so, it correctly gives you -0030. +1.
5

str.format() is the preferred way to do this if you are using Python >=2.6

>>> a=[1000, 200, 30]
>>> map("{0:05}".format, a)
['01000', '00200', '00030']

Comments

2

You can do it like this:

a = [1000,200,30]
b = ["%05d" % (i) for i in a]
print b

The number tells the width and the leading zero says that you want leading zeros.

Comments

1
map(lambda x:str(x).zfill(5),a)

2 Comments

I hate this answer since all that lambda stuff makes a mockery of my beautiful grade-school teaching language, but it is useful, so +1 :-)
@paxdiablo, it's also possible to pass a str.format as the first arg to map. See my answer
1

Look at formatting strings in Python.

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.