n00bie wants advice.

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Wed Jul 2 03:32:58 EDT 2008


On Tue, 01 Jul 2008 23:25:53 -0700, bsagert wrote:

> This simple script writes html color codes that can be viewed in a
> browser.  I used short form hex codes (fff or 000, etc) and my list
> has only six hex numbers otherwise the results get rather large. I
> invite criticism as to whether my code is "pythonic".

You should not rebind the name `list` because it shadows the built in type
of that name then.  A more descriptive name would be nice anyway, i.e.
`hex_digits`.  And strings are iterable too, so it's a bit shorter and
easier to type the digits a string.

Repeatedly concatenating strings with ``+=`` might be performance problem.
Python strings are immutable so this operation has to copy the involved
and growing strings over and over again.  Although the current CPython
implementation can optimize here in some cases, the usual idiom is to use
the `join()` method of strings to build a string from components in a list
or iterable.

Alternative implementation of your script:

from __future__ import with_statement

def main():
    html_template = ('<html><head><style>h1{margin:0}</style></head><body>\n'
                     '%s\n'
                     '</body></html>\n')
    header_template = '<h1 style="background:#%s">%s</h1>'
    hex_digits = '369bdf'
    colors = (a + b + c for a in hex_digits
                        for b in hex_digits
                        for c in hex_digits)
    html = html_template % '\n'.join(header_template % (c, c) for c in colors)
    with open('test.html', 'w') as html_file:
        html_file.write(html)

if __name__ == '__main__':
    main()



More information about the Python-list mailing list