2016-01-17 302 views
0

我有一個字符串像「一些字符\ x00 \ x80 \ x34,然後一些其他字符」。如何將常規字符轉換爲十六進制等價值,同時將\ x00轉換爲實際的00十六進制值? binascii.hexlify()認爲 '\', 'X', '0', '0' 作爲實際字符。python字符串與十六進制轉義十六進制值

後來編輯: 本身是由另一個函數生成的字符串。當我打印它時,它實際上打印「\ x00」。

+0

我發現了一個解決方案在這裏:http://stackoverflow.com/questions/3519125/converting-a-hex-string-representation-to-actual-bytes-in -蟒蛇 –

回答

0

目前還不清楚你問什麼,因爲binascii.hexlify應該工作:

>>> import binascii 
>>> s = "\x00\x80\x34" 
>>> binascii.hexlify(s) 
'008034' 
>>> s = "foobar \x00\x80\x34 foobar" 
>>> binascii.hexlify(s) 
'666f6f6261722000803420666f6f626172' 

foorbar = 666f6f6261722,空間= 20

https://docs.python.org/3/library/binascii.html

1

正如我理解你試圖只將不是十六進制值的字符轉換爲十六進制。如果你給一個你試圖轉換爲十六進制的樣本輸入字符串,這將有所幫助。

也可以使用內置的編碼和解碼方法轉換爲十六進制值。這應該照顧你想要做的事情。以下三行是我在機器的終端中運行的,並給出了您期望的輸出。我還附上了一張圖片來向你展示。希望它能幫助:

aStr = "Some characters \x00\x80\x34 and then some other characters" 
aStr.encode("hex") 
aStr.encode("hex").decode("hex") 

Here is the code I ran in my terminal.

相關問題