Newbie question, list comprehension
Hans Nowak
zephyrfalcon!NO_SPAM! at gmail.com
Fri Jun 6 18:12:19 EDT 2008
Johannes Bauer wrote:
> Hello group,
>
> I'm currently doing something like this:
>
> import time
> localtime = time.localtime(1234567890)
> fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % (localtime[0], localtime[1],
> localtime[2], localtime[3], localtime[4], localtime[5])
> print fmttime
>
> For the third line there is, I suppose, some awesome python magic I
> could use with list comprehensions. I tried:
>
> fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % ([localtime[i] for i in
> range(0, 5)])
The % operator here wants a tuple with six arguments that are integers, not a
list. Try:
fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % tuple(localtime[i] for i in
range(6))
> As it appearently passed the while list [2009, 02, 14, 0, 31, 30] as the
> first parameter which is supposed to be substituted by "%04d". Is there
> some other way of doing it?
In this case, you can just use a slice, as localtime is a tuple:
fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % localtime[:6]
Hope this helps! ^_^
--
Hans Nowak (zephyrfalcon at gmail dot com)
http://4.flowsnake.org/
More information about the Python-list
mailing list