Python 默认显示字符串的表示,除非您明确打印它们。 \x9d 是字符的repr(表示),如果您打印它,您会看到其他内容,具体取决于终端使用的编码和字体
>>> chr(157)
'\x9d'
>>> print repr(chr(157)) # equivalent to the above
'\x9d'
>>> print chr(157)
� # this appears as a question mark in a diamond shaped box on my system
但这并不会阻止您将数据写入文件。
编辑
如果通过“扩展ASCII”你指的是这个字符集http://en.wikipedia.org/wiki/Code_page_437,你应该可以使用
>>> print chr(157).decode('CP437')
¥
这将返回一个适合打印的 unicode 字符串(如果您的终端支持)。
编辑 2
在 Python 3.x 中有点不同,因为 ord 返回一个 unicode str。相反,您需要一个 bytes str(相当于 Python2.x str):
>>> bytes([157]) # this is equivalent to ord(157) in Python 2.x
b'\x9d'
>>> bytes([157]).decode('cp437') # decode this to a unicode str with the desired encoding
'¥'
>>> print(bytes([157]).decode('cp437')) # now it's suitable for printing
¥
确保在将数据写入文件时写入原始的bytes str,而不是 unicode(可打印)str:
>>> data = bytes([154, 155, 156, 157])
>>> print (data.decode('cp437')) # use decode for printing
Ü¢£¥
>>> with open('output.dat', 'wb') as f:
... f.write(data) # but not for writing to a file
...
4
>>> with open('output.dat', 'rb') as f:
... data = f.read()
... print(data)
... print(data.decode('cp437'))
...
b'\x9a\x9b\x9c\x9d'
Ü¢£¥