How to format all the elements of a list in Python?

4

In php, when I want to generate a array formatted, I use the array_map function.

So:

$numeros = range(1, 10);

array_map(function ($value) {
    return sprintf('%04', $value);
}, $numeros);

Return:

array('0001', '0002', '0003', '0004' ...);

In python , for this list range(1, 10) how could I do this same operation?

Is there any short and simple way to do this (same as or better than in PHP)?

    
asked by anonymous 28.10.2015 / 19:43

2 answers

5

Yes.

numeros = list(range(1, 10))
resultado = [str(x).zfill(4) for x in numeros]
    
28.10.2015 / 19:50
3

Just as a complement to the response from @CiganoMorrizonMender :

This operation, in Python , is called List Comprehensions .

It can be used to build lists in a very simple way.

If the purpose is to only create the formatted list, without having to have the unformatted value in a variable, we can simply make the following statement directly, without creating a variable before.

senhores = ['Senhor %s' % (nome) for nome in ['wallace', 'cigano', 'bigown']]

Return is:

['Senhor wallace', 'Senhor cigano', 'Senhor bigwon']
    
30.10.2015 / 15:48