这是一个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