Awkward format string

attn.steven.kuo at attn.steven.kuo at
Wed Aug 1 21:57:20 CEST 2007

On Aug 1, 9:42 am, beginner <zyzhu2... at> wrote:


> e is not complicated. It is a record that have 7 fields. In my program
> a function outputs a list of tuples, each is of type e, and now I just
> need to send them to a text file.
> I have no problem using classes and I do use them everywhere. But
> using classes does not solve my problem here. I will probably find
> myself doing:
> print  >>f, "%s\t%s\t%d\t%f\t%f\t%f\t%d" % (x.field1..strftime("%Y-%m-
> %d"), x.field2..strftime("%Y-%m-%d"), x.field3, x.field4, x.field5,
> x.field.6, x.field7)
> This is also tedious and error-prone.

You can implement a __str__ special method in a class.  You can
use 'type' to examine, well, the type of an object.  So:

from datetime import datetime

class PrettyDT(datetime):
    def __str__(self):
        return self.strftime('%Y-%m-%d')

e = (PrettyDT(2007, 8, 1), PrettyDT(2007, 8, 2),
        1, 2.0, 3.0, 4)

print '\t'.join(str(each) for each in e)

# Or even

format = { int: '%d', float: '%f', PrettyDT: '%s' }
format_string = '\t'.join(format[type(each)] for each in e)
print format_string % e;

Hope this helps,

More information about the Python-list mailing list