[英]How do I convert a string into bytes in python?
在我的代碼中,我使用utf-8編碼了一個字符串。 我得到輸出,將其轉換為字符串,然后將其發送到其他程序。 另一個程序獲取此字符串,但是,當我嘗試對該字符串進行解碼時,它給我一個錯誤,AttributeError:'str'對象沒有屬性'decode'。 我需要將編碼后的數據作為字符串發送,因為我的其他程序在json中接收到它。 我的第一個程序在python 3中,另一個程序在python 2中。
# my first program
x = u"宇宙"
x = str(x.encode('utf-8'))
# my other program
text = x.decode('utf-8')
print(text)
我應該怎么做才能將第二個程序收到的字符串轉換為字節,以便解碼工作?
正確回答此問題的最重要部分是有關如何將這些對象傳遞給Python2程序的信息:您正在使用JSON。
所以,和我在一起:
在程序1中執行.encode
步驟后,便有了一個byte對象。 通過在其上調用
str(...)
,您只是在該字節對象上放了一個轉義層,然后將其轉回一個字符串-但是當此字符串按原樣寫入文件或通過網絡傳輸時,它將將會再次編碼-所有非ASCII令牌通常都使用\\u\u003c/code>前綴和每個字符的代碼點進行轉義-但原始的中文字符本身現在已以utf-8編碼並進行了雙轉義。
Python的JSON加載方法已經將json數據的內容解碼為文本字符串:因此完全不需要解碼方法。
簡而言之 :要傳遞數據,只需在第一個程序中將原始文本編碼為JSON,並且在目標Python 2程序上的
json.load
之后不要進行任何解碼:
# my first program
x = "宇宙"
# No str-encode-decode dance needed here.
...
data = json.dumps({"example_key": x, ...})
# code to transmit json string by network or file as it is...
# my other program
text = json.loads(data)["example_key"]
# text is a Unicode text string ready to be used!
在執行操作時,您可能會得到雙倍編碼的文本-我將在Python 3控制台上對其進行模仿。 我將打印每個步驟的結果,以便您不了解正在發生的轉換。
In [1]: import json
In [2]: x = "宇宙"
In [3]: print(x.encode("utf-8"))
b'\xe5\xae\x87\xe5\xae\x99'
In [4]: text = str(x.encode("utf-8"))
In [5]: print(text)
b'\xe5\xae\x87\xe5\xae\x99'
In [6]: json_data = json.dumps(text)
In [7]: print(json_data)
"b'\\xe5\\xae\\x87\\xe5\\xae\\x99'"
# as you can see, it is doubly escaped, and it is mostly useless in this form
In [8]: recovered_from_json = json.loads(json_data)
In [9]: print(recovered_from_json)
b'\xe5\xae\x87\xe5\xae\x99'
In [10]: print(repr(recovered_from_json))
"b'\\xe5\\xae\\x87\\xe5\\xae\\x99'"
In [11]: # and if you have data like this in files/databases you need to recover:
In [12]: import ast
In [13]: recovered_text = ast.literal_eval(recovered_from_json).decode("utf-8")
In [14]: print(recovered_text)
宇宙
主要是您正在處理兩個不同的python版本,並且它具有庫問題。
六庫解決了這個問題。
六個提供了用於包裝Python 2和Python 3之間差異的簡單實用程序。它旨在支持無需修改即可在Python 2和3上運行的代碼庫。
使用該庫並以這種方式解碼。
import six
def bytes_to_str(s, encoding='utf-8'):
"""Returns a str if a bytes object is given."""
if six.PY2 and isinstance(s, bytes):
return s.decode(encoding)
return s
text = bytes_to_str(x)
print(text)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.