Search code examples
pythonunicodexlrd

Convert a python list having a mix of unicode values and floating numbers


So I am reading values from an excel and storing inside a list. But by default, it stored strings as unicode strings and numbers as floats. I want to convert unicode strings into normal strings and float to integer. How do I do that?

Here's my list:

import xlrd 
wb = xlrd.open_workbook("test.xlsx")
firstsheet = wb.sheet_by_index(0)
rows =1
rowvalues = []
while(rows <= (firstsheet.nrows)-1):
     rowvalues.extend(firstsheet.row_values(rows)) 
     rows+=1
print rowvalues

Output:

[121090999.0, 3454554455.0, u'Shantharam', 121090999.0, 5645.0, u'Puranik']

What I need:

[ 121090999,  3454554455,  'Shantharam', 121090999,  5645,  'Puranik' ]

Solution

  • You can use isinstance to check the type of the variable

    rows = [121090999.0, 3454554455.0, u'Shantharam', 121090999.0, 5645.0, u'Puranik']
    def convert_rows(rows):
        for kk,vv in enumerate(rows):        
            if isinstance(vv,float):
                rows[kk] = int(vv)
            if isinstance(vv,unicode):
                rows[kk] = vv.encode('ascii')
        return rows
    print( convert_rows(rows) )
    # prints [121090999, 3454554455L, 'Shantharam', 121090999, 5645, 'Puranik']