簡體   English   中英

如何將 'bytes' 的字符串表示形式轉換為 Python 中對應的 'utf-8'? (蟒蛇 3.7)

[英]How to convert a string representation of 'bytes' to its corresponding 'utf-8' in Python? (Python 3.7)

字節數據作為字符串存儲在變量中。

例如:x = "\x61\x62\x63"

我需要將其轉換為對應的 UTF-8。(在本例中為“abc”)。

我試圖將其轉換為字節,然后對其進行解碼,但結果是輸入本身。

>>> x = "\x61\x62\x63"
>>> x
'abc'
>>> bytes(x, 'utf-8')
b'abc'
>>> str(bytes(x, 'utf-8'))[2:-1]
'abc'

盡管我不建議在生產環境中使用eval ,但您可以執行以下操作:

import ast
x = r"\x61\x62\x63"
code = 'b"{0}"'.format(x)
b = ast.literal_eval(code)
b.decode('utf-8')

編輯:IIRC,格式字符串附帶了后來的 python 版本,所以使用'b"{0}".format(x)'

編輯:添加了 Mark Tolonen 的評論。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM