add leading zeros to a list of numbers in Python

前端 未结 1 1142
半阙折子戏
半阙折子戏 2020-12-30 04:18

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 t

相关标签:
1条回答
  • 2020-12-30 04:53

    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']
    
    0 讨论(0)
提交回复
热议问题