這是一個Python 101類型的問題,但當我嘗試使用一個似乎將字符串輸入轉換爲字節的包時,它讓我感到困惑。如何在Python 3中的字節和字符串之間進行轉換?
正如您將在下面看到的,我爲自己找到了答案,但我覺得這值得在這裏記錄,因爲我花時間挖掘發生了什麼事情。它似乎對Python 3是通用的,所以我沒有提到我正在玩的原始包;它似乎並不是一個錯誤(只是特定的包有.tostring()
方法顯然不生產什麼,我理解爲一個字符串...)
我的測試程序是這樣的:
import mangler # spoof package
stringThing = """
<Doc>
<Greeting>Hello World</Greeting>
<Greeting>你好</Greeting>
</Doc>
"""
# print out the input
print('This is the string input:')
print(stringThing)
# now make the string into bytes
bytesThing = mangler.tostring(stringThing) # pseudo-code again
# now print it out
print('\nThis is the bytes output:')
print(bytesThing)
從這個代碼的輸出給出了這樣的:
This is the string input:
<Doc>
<Greeting>Hello World</Greeting>
<Greeting>你好</Greeting>
</Doc>
This is the bytes output:
b'\n<Doc>\n <Greeting>Hello World</Greeting>\n <Greeting>\xe4\xbd\xa0\xe5\xa5\xbd</Greeting>\n</Doc>\n'
因此,有必要能夠字節和字符串之間進行轉換,以避免與非ASCII字符正在變成官樣文章結束了。
[This question](http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3)在答案中給出了更多細節,但我認爲下面的簡要回答更加清晰。 – Bobble