Search code examples
pythonexcelxlrd

Python Value Types (int, float, str)


I have an Excel sheet with the data as pictured:Cisco Call Handlers

I'm working with Python 3 and reading data from the Excel sheet but since it has both integers and strings, I cannot specify the data type. What's the best way to handle value types? At first, the integers would print of type "float" along with a trailing ".0" so I placed an apostrophe before the number of each cell and this resolved the issue but integers now print as type string. I want to build logic around the different types so what's the best way to go about this? This is what I had in mind before I realized the integers now print as type string:

if type(value[x]) == str:
    do x
if type(value[x]) == int:
    do y

Another option I considered was to keep the type float and build logic around that but I would need regex help to remove the trailing ".0" after each cell that had integers. This is what it would print before I placed apostrophes in each cell with numbers:

0 ['DisplayName', 'Extension', 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]

value is created as follows:

values = dict()
for idx in range(1, xlrdsheet.nrows):
    values[idx] = xlrdsheet.row_values(idx)
for key, value in values.items():
    print(key, value)

Solution

  • I'm guessing you are reading these values from the Excel sheet as text: You can use regex to check wether your value consists of numbers( r"[0-9]*") or letters( r"[a-bA-B]*") and convert it respectively. Or:

    try:
        number = int(val)
    except ValueError:
        text = val