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)?
The guy put a "Yes" just not to get just code. I liked this function
zfill
. Good to know there’s such a thing inpython
, without having to keep creating– Wallace Maxters
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)]– jsbueno
Alias - in this case there is no need to use
list(range(..))
- the behavior offor
is identical for both the Python 2 range and the Python 3 range– jsbueno
@jsbueno, our pythonico boy
– Wallace Maxters