我从一个webservice中使用requests
模块获取了一个Unicode字符串,其中包含二进制文档的字节(例如PCL)。其中一个字节的值为248,尝试对其进行base64编码会导致以下错误:
In [68]: base64.b64encode(response_dict['content']+'\n')
---------------------------------------------------------------------------
UnicodeEncodeError Traceback (most recent call last)
C:\...\<ipython-input-68-8c1f1913eb52> in <module>()
----> 1 base64.b64encode(response_dict['content']+'\n')
C:\Python27\Lib\base64.pyc in b64encode(s, altchars)
51 """
52 # Strip off the trailing newline
---> 53 encoded = binascii.b2a_base64(s)[:-1]
54 if altchars is not None:
55 return _translate(encoded, {'+': altchars[0], '/': altchars[1]})
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf8' in position 272: ordinal not in range(128)
In [69]: response_dict['content'].encode('base64')
---------------------------------------------------------------------------
UnicodeEncodeError Traceback (most recent call last)
C:\...\<ipython-input-69-7fd349f35f04> in <module>()
----> 1 response_dict['content'].encode('base64')
C:\...\base64_codec.pyc in base64_encode(input, errors)
22 """
23 assert errors == 'strict'
---> 24 output = base64.encodestring(input)
25 return (output, len(input))
26
C:\Python27\Lib\base64.pyc in encodestring(s)
313 for i in range(0, len(s), MAXBINSIZE):
314 chunk = s[i : i + MAXBINSIZE]
--> 315 pieces.append(binascii.b2a_base64(chunk))
316 return "".join(pieces)
317
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf8' in position 44: ordinal not in range(128)
我觉得这有点令人惊讶,因为248在无符号字节范围内(可以保存在字节字符串中),但我的真正问题是:编码这个字符串的最佳或正确方法是什么? 我目前的解决方法是:
In [74]: byte_string = ''.join(map(compose(chr, ord), response_dict['content']))
In [75]: byte_string[272]
Out[75]: '\xf8'
这似乎可以正常工作,生成的byte_string
能够进行base64编码,但是似乎应该有更好的方法。是否有其他方法?
unicode
字符串的代码点并将其视为字节。这最好是可疑的,因为不能保证代码点甚至在0-255范围内。更糟糕的是,之后没有人会知道如何解释这个字节字符串,因为它是以自定义的未定义编码形式存在的。 - Cameron