convert COM obj to integer

Steve M sjmaster at gmail.com
Wed Nov 2 17:55:31 EST 2005


I don't know exactly what a COM object is, but those aren't them. The
win32com package takes care of converting everything to Python types.
The excel call returns a tuple of tuples. That is, the outer tuple is
the sequence of rows, and each such row is itself a tuple with one
member per column requested. Since you only request one column, it is a
one-item-long tuple, also called a 1-tuple. That is demonstrated by the
result of print'ing the list.

By the way, you shouldn't use 'list' as a name because it is also the
name of a built-in function. And it isn't a list anyway, it's a tuple.

Now, each number is in fact already a primitive Python object of type
float. (The asterisk is a unicode string.) So you want to convert the
floats into integers, and it looks like you want to round rather than
truncate.
----
table = xlApp.ActiveWorkbook.ActiveSheet.Range("Q13:Q36")

converted_values = []

for row in table:
    value = row[0] #get the first (and only) item in the tuple
    try:
        value = round(value)
    except TypeError: #value is not a float
        value = None
    else:
        value = int(value) #turn the float into an int
    converted_values.append(value)
print converted_values
----

By the way, if you wonder how I knew to catch the TypeError, I just
fired up the interactive Python interpreter, and typed this: round(u'*')




More information about the Python-list mailing list