这是一个Python 101类型的问题,但当我尝试使用一个似乎将我的字符串输入转换为字节的包时,它曾经让我困惑了一段时间。
如下所示,我自己找到了答案,但由于花费了我很长时间才弄清楚发生了什么,我觉得记录在这里是值得的。这似乎是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字符被转换成乱码。所需翻译内容:
So, there is a need to be able to convert between bytes and strings, to avoid ending up with non-ascii characters being turned into gobbledegook.