Python 中提供了幾種將十六進(jìn)制值轉(zhuǎn)換為字符串的方法,下面將介紹其中的三種方法。
1. 使用 bytes.fromhex() 方法
bytes.fromhex()
方法可以將十六進(jìn)制字符串轉(zhuǎn)換為字節(jié)串,然后再將字節(jié)串轉(zhuǎn)換為字符串。例如:
hex_str = "48656c6c6f20576f726c64"
byte_str = bytes.fromhex(hex_str)
str_result = byte_str.decode("utf-8")
print(str_result) # 輸出:Hello World
其中,bytes.fromhex()
方法將十六進(jìn)制字符串轉(zhuǎn)換為字節(jié)串,byte_str.decode("utf-8")
方法將字節(jié)串轉(zhuǎn)換為字符串。
需要注意的是,bytes.fromhex()
方法只能處理沒有空格的十六進(jìn)制字符串,如果輸入的十六進(jìn)制字符串包含空格,需要先將空格刪除,例如:
hex_str = "48 65 6c 6c 6f 20 57 6f 72 6c 64"
hex_str = hex_str.replace(" ", "") # 刪除空格
byte_str = bytes.fromhex(hex_str)
str_result = byte_str.decode("utf-8")
print(str_result) # 輸出:Hello World
2. 使用 binascii.unhexlify() 方法
binascii.unhexlify()
方法可以將十六進(jìn)制字符串轉(zhuǎn)換為字節(jié)串,然后再將字節(jié)串轉(zhuǎn)換為字符串。例如:
import binascii
hex_str = "48656c6c6f20576f726c64"
byte_str = binascii.unhexlify(hex_str)
str_result = byte_str.decode("utf-8")
print(str_result) # 輸出:Hello World
其中,binascii.unhexlify()
方法將十六進(jìn)制字符串轉(zhuǎn)換為字節(jié)串,byte_str.decode("utf-8")
方法將字節(jié)串轉(zhuǎn)換為字符串。
需要注意的是,binascii.unhexlify()
方法只能處理沒有空格的十六進(jìn)制字符串,如果輸入的十六進(jìn)制字符串包含空格,需要先將空格刪除,例如:
import binascii
hex_str = "48 65 6c 6c 6f 20 57 6f 72 6c 64"
hex_str = hex_str.replace(" ", "") # 刪除空格
byte_str = binascii.unhexlify(hex_str)
str_result = byte_str.decode("utf-8")
print(str_result) # 輸出:Hello World
3. 使用 codecs.decode() 方法
codecs.decode()
方法可以將十六進(jìn)制字符串直接轉(zhuǎn)換為字符串。例如:
import codecs
hex_str = "48656c6c6f20576f726c64"
str_result = codecs.decode(hex_str, "hex").decode("utf-8")
print(str_result) # 輸出:Hello World
其中,codecs.decode()
方法將十六進(jìn)制字符串直接轉(zhuǎn)換為字節(jié)串,byte_str.decode("utf-8")
方法將字節(jié)串轉(zhuǎn)換為字符串。
需要注意的是,codecs.decode()
方法只能處理沒有空格的十六進(jìn)制字符串,如果輸入的十六進(jìn)制字符串包含空格,需要先將空格刪除,例如:文章來源:http://www.zghlxwxcb.cn/news/detail-422683.html
import codecs
hex_str = "48 65 6c 6c 6f 20 57 6f 72 6c 64"
hex_str = hex_str.replace(" ", "") # 刪除空格
str_result = codecs.decode(hex_str, "hex").decode("utf-8")
print(str_result) # 輸出:Hello World
這三種方法都可以將十六進(jìn)制值轉(zhuǎn)換為字符串,選擇哪一種方法取決于你的使用場(chǎng)景和偏好。需要注意的是,如果十六進(jìn)制字符串不合法,這些方法都會(huì)拋出異常,需要對(duì)輸入的十六進(jìn)制字符串進(jìn)行合法性檢查。文章來源地址http://www.zghlxwxcb.cn/news/detail-422683.html
到了這里,關(guān)于python 如何將十六進(jìn)制值轉(zhuǎn)換為字符串?的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!