Unicode编码错误:'ascii'编解码器无法编码位置0-6的字符:序数不在范围(128)内
我有一个叫做 elm 的 lxml.objectify.StringElement 对象,内容是:
u'\u266b\u266b\u266b\u266b\u266b\u266b\u266bHow do you get a job on the Yahoo staff when you are older?\u266b\u266b\u266b\u266b\u266b?'
我想把它转换成一个字符串(str):
str(elm)
但是我遇到了这个错误:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-6: ordinal not in range(128)
2 个回答
0
你不需要进行任何转换,文件内容默认就是unicode格式。只要去掉str
就可以了。所有的字符串方法都可以用在unicode上,所以分割字符串是没问题的。如果你想从某个对象中得到unicode格式,试着用unicode
代替str
。
0
我遇到过类似的情况,像这样的方法对我有效(我现在找不到那个代码了):
a=u'\u266b\u266b\u266b\u266b\u266b\u266b\u266bHow do you get a job on the Yahoo staff when you are older?\u266b\u266b\u266b\u266b\u266b?'
print bytes(a.encode('utf-32'))
但是我用你的字符串时得到了这个结果:
��k&k&k&k&k&k&k&How do you get a job on the Yahoo staff when you are older?k&k&k&k&k&?
哈哈!我知道这可能对你没有直接帮助,但也许这能为你指明一个方向。顺便说一下,你可以试试Python 3+,它在处理unicode方面要好得多。