Search code examples
pythonregextypeerrorquantifiers

TypeError: unsupported operand type(s) for /: 'str' and 'int' for


I am using python 3.7

My list data looks like this

[['file1.o', '.text', '0x30'], ['file2.o', '.initvector', '0x36'], ['15', '31', '0x72']]

My code

For parsing the file

 c = re.compile("^\w+.*(\w+)\s+([\.\w]+)\s+([\w\.]+).*$")

Printing to a csv file uses

 for i in module_info:
    row = [i[0], i[1], "%d" %(i[2]/1024)]
    writer.writerow(row) 

I am getting this error:

TypeError: unsupported operand type(s) for /: 'str' and 'int'

How can I fix this?

I have updated the answer. Appreciate all contributions


Solution

  • The error is generating in i[2]/1024 this snippet of code, where the i[2] is actually interpreted as a string and 1024 as an int. That's why the error is there.

    You have to convert the string into a number

    To convert the hex string into a decimal number, use int(i[2], 16)

    To convert the hex string into a decimal number, use bin(int(i[2], 16))

    Use your preferred type of conversion and use it. I hope that'll solve your issue.