Awkward format string

beginner zyzhu2000 at gmail.com
Thu Aug 2 10:55:28 EDT 2007


On Aug 2, 3:32 am, Bruno Desthuilliers <bruno.
42.desthuilli... at wtf.websiteburo.oops.com> wrote:
> beginner a écrit :
>
> > Hi,
>
> > In order to print out the contents of a list, sometimes I have to use
> > very awkward constructions. For example, I have to convert the
> > datetime.datetime type to string first, construct a new list,
>
> s/list/tuple/
>
> > and then
> > send it to print. The following is an example.
>
> >    x=(e[0].strftime("%Y-%m-%d"), e[1].strftime("%Y-%m-%d"))+e[2:]
> >    print  >>f, "%s\t%s\t%d\t%f\t%f\t%f\t%d" % x
>
> > e is a tuple. x is my new tuple.
>
> > Does anyone know better ways of handling this?
>
>  >>> from datetime import datetime
>  >>> dt = datetime(2007,8,2)
>  >>> dt
> datetime.datetime(2007, 8, 2, 0, 0)
>  >>> str(dt)
> '2007-08-02 00:00:00'
>  >>> "%s" % dt
> '2007-08-02 00:00:00'
>  >>> dt.date()
> datetime.date(2007, 8, 2)
>  >>> str(dt.date())
> '2007-08-02'
>
> Do you really need datetime objects ? If not, using date objects instead
> would JustWork(tm) - at least until someone ask you to use another date
> format !-)
>
> Else, and since you seem to have a taste for functional programming:
>
> from datetime import datetime
> from functools import partial
>
> def iformat(e):
>      fake = lambda obj, dummy: obj
>      for item in e:
>          yield getattr(item, 'strftime', partial(fake, item))('%Y-%m-%d')
>
> e = (datetime(2007,8,1),datetime(2007,8,2) ,42, 0.1, 0.2, 0.3, 1138)
> print tuple(iformat(e))
> print "%s\t%s\t%d\t%f\t%f\t%f\t%d" % tuple(iformat(e))

Thanks.

The 'functional' taste is still under development. It hasn't reached
production quality yet. :-)




More information about the Python-list mailing list