[英]Python3 - How to convert a string to hex
我試圖逐個字符串轉換為十六進制,但我不能在Python3中找出它。
在較舊的python版本中,我在下面的工作:
test = "This is a test"
for c in range(0, len(test) ):
print( "0x%s"%string_value[i].encode("hex") )
但是使用python3我收到以下錯誤:
LookupError:'hex'不是文本編碼; 使用codecs.encode()來處理任意編解碼器。
任何人都可以幫助告訴我python3中的轉換。
提前致謝
在python 3x中使用binascii
而不是hex:
>>> import binascii
>>> binascii.hexlify(b'< character / string>')
打印:
for c in test:
print(hex(ord(c)))
轉換:
output = ''.join(hex(ord(c)) for c in test)
或者輸出中沒有'0x':
output = ''.join(hex(ord(c))[2:] for c in test)
怎么樣:
>>> test = "This is a test"
>>> for c in range(0, len(test) ):
... print( "0x%x"%ord(test[c]))
...
0x54
0x68
0x69
0x73
0x20
0x69
0x73
0x20
0x61
0x20
0x74
0x65
0x73
0x74
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.