當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Hex轉String用法及代碼示例

十六進製表示是以人類可讀的形式表達二進製數據的常見格式。將十六進製值轉換為字符串是 Python 中的一項常見任務,開發人員經常尋求高效且簡潔的方法。在本文中,我們將探索在 Python 中將十六進製轉換為字符串的不同方法。

在 Python 中將十六進製轉換為字符串

以下是將十六進製轉換為字符串的方法Python

  • 使用列表理解
  • 使用編解碼器.decode()
  • 使用字節。fromhex()

使用列表理解將十六進製轉換為字符串

在此示例中,以下方法涉及使用列表理解來迭代十六進製字符串,將每對字符轉換為整數,然後將它們連接為string.

Python3


# Example hex values
hex_values = "53686976616e6720546f6d6172" 
result_string = ''.join([chr(int(hex_values[i:i+2], 16)) for i in range(0, len(hex_values), 2)])
print(result_string)
print(type(result_string))
輸出
Shivang Tomar
<class 'str'>


使用 codecs.decode 將十六進製轉換為字符串

在這個例子中,下麵的代碼codecsPython 中的 module 提供了一種處理編碼的通用方法。通過使用codecs.decode(),我們可以直接將十六進製字符串轉換為字符串。

Python3


import codecs
# Example hex values
hex_values = "507974686f6e" 
result_string = codecs.decode(hex_values, 'hex').decode('utf-8')
print(result_string)
print(type(result_string))
輸出
Python
<class 'str'>


使用字節將十六進製轉換為字符串。fromhex()

在這個例子中,我們使用bytes.fromhex()Python 中的方法旨在從十六進製字符串創建字節對象。將其與decode方法允許我們獲取一個字符串。

Python3


# Example hex values
hex_values = "4765656b73666f724765656b73" 
byte_values = bytes.fromhex(hex_values)
result_string = byte_values.decode('utf-8')
print(result_string)
print(type(result_string))
輸出
GeeksforGeeks
<class 'str'>




相關用法


注:本文由純淨天空篩選整理自venkateshk1220大神的英文原創作品 Convert Hex to String in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。