如何在python中转换十六进制?

时间:2017-06-06 11:38:56

标签: python

我的文件在每行中包含一些十六进制数字。例如:

5B35E8DF4A709CA16A1C8BC29022E83C
28958FA134D53BE6F382D04DC9891922
C67FC50F905F043EBEFEBFAF243B8744
99DCD61A89EE5553DDCA44378C3CE3C6
...........

我想将它们从大写转换为小写。例如:

5b35e8df4a709ca16a1c8bc29022e83c

Srcpath  ='Uppercase_File'
Destpath ='Lowercase_File'
with open(Srcpath, 'r') as f:
    with open(Destpath, 'w') as fp:
        for key in f:
            print(key)
            #key_Separated=[key[i:i+2] for i in range(0, len(key), 2)]
            rejoined = key.replace(" ","").decode('hex')
            print(rejoined)
            fp.write(rejoined)
    fp.close()

我的代码给了我这个错误:

rejoined = key.decode('hex')
File "/usr/lib64/python2.7/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Non-hexadecimal digit found

1 个答案:

答案 0 :(得分:2)

您可以使用它将值从十进制转换为十六进制:

>>> hex(65)
'0x41'

但如果您只想将字母转换为小写,为什么不使用.lower()方法:

>>> s = "AABA67A79A"
>>> s.lower()
'aaba67a79a'

https://docs.python.org/2/library/string.html