How to format all elements of a list in Python?

Asked

Viewed 1,685 times

5

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

Thus:

$numeros = range(1, 10);

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

Returns:

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

Already in python, for that list range(1, 10) how could I do that same operation?

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

2 answers

5


Yes.

numeros = list(range(1, 10))
resultado = [str(x).zfill(4) for x in numeros]
  • The guy put a "Yes" just not to get just code. I liked this function zfill. Good to know there’s such a thing in python, without having to keep creating

  • 3

    The solution is correct, but zfill is rarely used. In general the method is used format of the strings, which has a whole mini-formatting language and can do a lot more than just fill zeros. With format, it would be: `result = ["{:04d}". format(x) for x in range(1,10)]

  • 3

    Alias - in this case there is no need to use list(range(..)) - the behavior of for is identical for both the Python 2 range and the Python 3 range

  • @jsbueno, our pythonico boy

3

Only as a complement to the @Ciganomorrizonmender:

This operation, in Python, is called List Comprehensions.

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

If the goal is only to create the formatted list, without the need to have the non-formatted value in a variable, we can simply already 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']

Browser other questions tagged

You are not signed in. Login or sign up in order to post.