Write different hex-values in Python2 and Python3

大憨熊 提交于 2019-12-20 03:55:17

问题


I'm currently porting a Python2 script to Python3 and have problems with this line:

print('\xfe')

When I run it with Python2 python test.py > test.out, than the file consists of the hex-values FE 0A, like expected.

But when I run it with Python3 python3 test.py > test.out, the file consists of the hex-values C3 BE 0A.

What's going wrong here? How can I receive the desired output FE 0A with Python3.


回答1:


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') ).




回答2:


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?




回答3:


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.



来源:https://stackoverflow.com/questions/32017389/write-different-hex-values-in-python2-and-python3

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