在python3中将ascii转换为hex

2024-09-30 22:15:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着把ascii转换成十六进制值。但我的剧本有时奏效,有时行不通。我想知道为什么。代码如下:

ascii码=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')

我想要ascii_to_hex=423133353135303638

有时代码可以正常工作,但通常我会遇到如下错误:; enter image description here


Tags: to代码inforhaveasciirangech
1条回答
网友
1楼 · 发布于 2024-09-30 22:15:46

看起来并不是所有的单元格都有与之相关的值。当单元格没有值时,ascii_ch = sheet['C%s'%(i+2)].value会将ascii_ch设置为None。在下一行中,迭代ascii_ch。但是在None上迭代没有任何意义!在

你可能要检查一下,像这样:

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

相关问题 更多 >