Purgoufr
Purgoufr

Reputation: 962

Convert ascii to hex in Python 3

I try to convert ascii to hex value. But my script sometimes working, sometimes does not work. I wonder why. Code likes below:

ascii_ch = B13515068

for i in range(50):  #In excel I have 50 row
    ascii_ch = sheet['C%s'%(i+2)].value  #after C2, convert hex
    ascii_to_hex= "".join("{:02x}".format(ord(c)) for c in ascii_ch )
    sheet['I%s'%(i+2)] = ascii_to_hex
    wb.save('a.xlsx')

I want to ascii_to_hex= 423133353135303638

Sometimes code works properly, but Generally I get an error like below; enter image description here

Upvotes: 0

Views: 842

Answers (1)

phihag
phihag

Reputation: 287825

It looks like not all cells actually have values associated with them. When a cell has no value, ascii_ch = sheet['C%s'%(i+2)].value will set ascii_ch to None. In the next line, you iterate over ascii_ch. But it does not make any sense to iterate over None!

You probably want to check for that, like this:

for i in range(50):  #In excel I have 50 row
    ascii_ch = sheet['C%s'%(i+2)].value  #after C2, convert hex
    if ascii_ch is None:
        # Maybe warn the user that a value is missing?
        continue  # go on to the next cell

Upvotes: 1

Related Questions