Write different hex-values in Python2 and Python3

夙愿已清 提交于 2019-12-02 03:48:51

The byte-sequence C3 BE is the UTF-8 encoded representation of the character U+00FE.

Python 2 handles strings as a sequence of bytes rather than characters. So '\xfe' is a str object containing one byte.

In Python 3, strings are sequences of (Unicode) characters. So the code '\xfe' is a string containing one character. When you print the string, it must be encoded to bytes. Since your environment chose a default encoding of UTF-8, it was encoded accordingly.

How to solve this depends on your data. Is it bytes or characters? If bytes, then change the code to tell the interpreter: print(b'\xfe'). If it is characters, but you wanted a different encoding then encode the string accordingly: print( '\xfe'.encode('latin1') ).

jfs

print '\xfe' Python 2 code is roughly equivalent to this Python 3 code:

sys.stdout.buffer.write(b'\xfe' + os.linesep.encode())

while print('\xfe') Python 3 code is roughly equivalent to this Python 3 code:

sys.stdout.buffer.write((u'\xfe' + os.linesep).encode(sys.stdout.encoding))

In the first case Python prints bytes. In the second case, it prints Unicode and the result depends on your environment (locale).

>>> u'\xfe'.encode('utf-8')
b'\xc3\xbe'

To print text, always use Unicode in Python. Do not hardcode the character encoding used by the current environment in your script.

To print binary data such as image data, compressed data (gzip), encrypted data, see How to write bytes to a file in Python 3 without knowing the encoding?

The print(argument) converts the argument using str() (if neccessary) and then it calls file.write(string). The file is the optional argument of the print(), and it defaults to sys.stdout. It means that you should be able to do the same with sys.stdout.write(str(argument) + '\n'). So, the result depends on the used encoding that you can get from sys.stdout.encoding. If you pass another file argument, then the file object have to be open for writing in the text mode, and possibly a different encoding may be applied.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!