Best way to generate alternate toggling values in a loop?

Debajit Adhikary debajit1 at gmail.com
Wed Oct 17 19:55:53 EDT 2007


I'm writing this little Python program which will pull values from a
database and generate some XHTML.

I'm generating a <table> where I would like the alternate <tr>'s to be

<tr class="Even">
and
<tr class="Odd">

What is the best way to do this?

I wrote a little generator (code snippet follows). Is there a better
(more "Pythonic") way to do this?


# Start of Code

def evenOdd():
    values = ["Even", "Odd"]
    state = 0
    while True:
        yield values[state]
        state = (state + 1) % 2


# Snippet

    trClass = evenOdd()
    stringBuffer = cStringIO.StringIO()

    for id, name in result:
        stringBuffer.write('''
        <tr class="%s">
            <td>%d</td>
            <td>%s</td>
        </tr>
        '''
        %
        (trClass.next(), id, name))


# End of Code




More information about the Python-list mailing list