这是一个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)
Run Code Online (Sandbox Code Playgroud)
此代码的输出给出了:
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'
Run Code Online (Sandbox Code Playgroud)
因此,需要能够在字节和字符串之间进行转换,以避免最终将非ascii字符转换为gobbledegook.