在Python2和Python3中编写不同的十六进制值 [英] Write different hex-values in Python2 and Python3
问题描述
我当前正在将Python2脚本移植到Python3,并在此行遇到问题:
I'm currently porting a Python2 script to Python3 and have problems with this line:
print('\xfe')
当我使用Python2 python test.py > test.out
运行它时,文件像预期的那样由十六进制值FE 0A
组成.
When I run it with Python2 python test.py > test.out
, than the file consists of the hex-values FE 0A
, like expected.
但是当我使用Python3 python3 test.py > test.out
运行它时,该文件由十六进制值C3 BE 0A
组成.
But when I run it with Python3 python3 test.py > test.out
, the file consists of the hex-values C3 BE 0A
.
这是怎么回事?如何使用Python3接收所需的输出FE 0A
.
What's going wrong here? How can I receive the desired output FE 0A
with Python3.
推荐答案
The byte-sequence C3 BE
is the UTF-8 encoded representation of the character U+00FE.
Python 2将字符串作为字节序列而不是字符来处理.因此'\xfe'
是一个包含一个字节的str
对象.
Python 2 handles strings as a sequence of bytes rather than characters. So '\xfe'
is a str
object containing one byte.
在Python 3中,字符串是(Unicode)字符的序列.因此,代码'\xfe'
是包含一个字符的字符串.当您打印字符串时,必须将其编码为字节.由于您的环境选择了UTF-8的默认编码,因此已对其进行了相应的编码.
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.
如何解决此问题取决于您的数据.是字节还是字符?如果是字节,则更改代码以告知解释器:print(b'\xfe')
.如果它是字符,但是您希望使用不同的编码,则对字符串进行相应的编码:print( '\xfe'.encode('latin1') )
.
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') )
.
这篇关于在Python2和Python3中编写不同的十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!