我掉进了unicode地狱。
我的环境在 unix,python 2.7.3
LC_CTYPE=zh_TW.UTF-8
LANG=en_US.UTF-8
我正在尝试以人类可读格式转储十六进制编码数据,这是简化的代码
#! /usr/bin/env python
# encoding:utf-8
import sys
s=u"readable\n" # previous result keep in unicode string
s2="fb is not \xfb" # data read from binary file
s += s2
print s # method 1
print s.encode('utf-8') # method 2
print s.encode('utf-8','ignore') # method 3
print s.decode('iso8859-1') # method 4
# method 1-4 display following error message
#UnicodeDecodeError: 'ascii' codec can't decode byte 0xfb
# in position 0: ordinal not in range(128)
f = open('out.txt','wb')
f.write(s)
我只想打印出 0xfb。
我应该在这里描述更多。关键是's += s2'。where s 将保留我之前解码的字符串。s2 是下一个应该附加到 s 中的字符串。
如果我修改如下,它会发生在写文件上。
s=u"readable\n"
s2="fb is not \xfb"
s += s2.decode('cp437')
print s
f=open('out.txt','wb')
f.write(s)
# UnicodeEncodeError: 'ascii' codec can't encode character
# u'\u221a' in position 1: ordinal not in range(128)
我希望 out.txt 的结果是
readable
fb is not \xfb
或者
readable
fb is not 0xfb
[解决方案]
#! /usr/bin/env python
# encoding:utf-8
import sys
import binascii
def fmtstr(s):
r = ''
for c in s:
if ord(c) > 128:
r = ''.join([r, "\\x"+binascii.hexlify(c)])
else:
r = ''.join([r, c])
return r
s=u"readable"
s2="fb is not \xfb"
s += fmtstr(s2)
print s
f=open('out.txt','wb')
f.write(s)