Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

string - add leading zeros to a list of numbers in Python

I am new to Python. I am trying to adjust the format of a list which looks like below:

data=[1,10,313,4000,51234,123456]

and I would like to convert them to a list of strings with leading zeros:

result=['000001','000010','000313','004000','051234','123456']

each of the element has 6 digits.

I know for a single number X, I can do:

str(X).zfill(6)

but I am not sure how to apply this to a list. I would like to solve this problem without using a for loop.

Anyone could help? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Apply the same zfill function in a list comprehension, like this

>>> [str(item).zfill(6) for item in data]
['000001', '000010', '000313', '004000', '051234', '123456']

Alternatively, you can use the string's format method, with format specifiers, like this

>>> ["{:06d}".format(item) for item in data]
['000001', '000010', '000313', '004000', '051234', '123456']

If you are going to do the formatting more often, then you can store that in a variable, like this

>>> formatter = "{:06d}".format
>>> [formatter(item) for item in data]
['000001', '000010', '000313', '004000', '051234', '123456']

If you are using Python 2.x, then you can use map and the formatter function, like this

>>> map(formatter, data)
['000001', '000010', '000313', '004000', '051234', '123456']

If you are using Python 3.x, map returns an iterable map object. So, you need to explicitly create a list, like this

>>> list(map(formatter, data))
['000001', '000010', '000313', '004000', '051234', '123456']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...