【问题标题】:Convert ascii to hex in Python 3在 Python 3 中将 ascii 转换为十六进制
【发布时间】:2017-08-25 09:42:32
【问题描述】:

我尝试将 ascii 转换为十六进制值。但我的脚本有时工作,有时不工作。我想知道为什么。代码如下:

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')

我要 ascii_to_hex=423133353135303638

有时代码可以正常工作,但通常我会收到如下错误;

【问题讨论】:

  • 阅读错误信息?
  • 我在行尾分享了错误信息; ascii_to_hex= "".join("{:02x}".format(ord(c)) for c in ascii_ch ) TypeError: 'NoneType' object is not iterable
  • 嗯,是的,我知道。但看起来你没看过。
  • 有趣的是代码有时有效,有时却报错。
  • 那一点也不有趣。

标签: python string python-3.x hex ascii


【解决方案1】:

看起来并非所有单元格实际上都有与之关联的值。当单元格没有值时,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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 2019-10-20
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多