[英]Converting a string formatted in hex in Python to binary data correctly
我有一個格式化為 '\\x00\\x00\\x00\\x00' 的字符串,需要對其進行格式化,以便在打印時,它在控制台中顯示為 b'\\x00\\x00\\x00\\x00'
我該怎么做呢?
編輯:我有一個不同版本的代碼打印出一個用 b'\\xf4\\x00\\x00\\x00' 等格式的字符串,並在我的電腦上打印 '\\xf4\\x00\\x00\\x00'
只需在字符串之前添加 b 文字,這樣您就可以將字符串定義為字節
# example
s = b"\x00\x00\x00\x00"
print(s)
相反,如果您從其他地方接收字符串並且您沒有手動編寫它,您可以將字符串編碼為字節
# an other example
# let's pretend that we received the value from, say, a function
s = "\x00\x00\x00\x00".encode() # again, pretend that this value has just been retrieved from a function
print(s)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.