tuple2csv snipplet

Skip Montanaro skip at pobox.com
Wed Jul 4 05:36:15 EDT 2001


    Shakeeb> ... convert tuples (generated from an SQL query) into comma
    Shakeeb> separated values.... is there a better way to do this?

Without reimplementing what you and others have already done, I suggest that
instead of stringifying the tuple and using regular expressions to convert
the fields that you consider looping over the tuple and constructing a list
of values that contains the appropriate strings, which you can then
string.join with commas:

    def tuple2csv(t):
        import types
        newt = []
        for elt in t:
            if elt is None:
                newt.append("")
                continue
            if (isinstance(elt, types.IntType) or
                isinstance(elt, types.FloatType)):
                newt.append(str(elt))
                continue
            if isinstance(elt, types.StringType):
               ... do the more complex string quote escaping, etc ...
        return ",".join(newt)

-- 
Skip Montanaro (skip at pobox.com)
(847)971-7098




More information about the Python-list mailing list