问题:urllib.quote(xxx)
运行后报错*** KeyError: u'\uxx'
原因:看下xxx
类型:<type 'unicode'>
,而urllib.quote(params)
中的params
就是字符串,只能猜测该字符串的编码不符合要求,所以对xxx
进行编码
解决:urllib.quote(xxx.encode("utf-8"))
或者urllib.quote(str(xxx))
示例如下:
>>> import urllib >>> xxx = u'[{"test":"测试"}]' >>> urllib.quote(xxx) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 1298, in quote return ''.join(map(quoter, s)) KeyError: u'\u6d4b' >>> type(xxx) <type 'unicode'> >>> urllib.quote(xxx.encode("utf-8")) '%5B%7B%22test%22%3A%22%E6%B5%8B%E8%AF%95%22%7D%5D' >>> urllib.quote(str(xxx)) Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode characters in position 10-11: ordinal not in range(128) >>> import sys >>> sys.setdefaultencoding('utf-8') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'setdefaultencoding' >>> reload(sys) <module 'sys' (built-in)> >>> sys.setdefaultencoding('utf-8') >>> urllib.quote(str(xxx)) '%5B%7B%22test%22%3A%22%E6%B5%8B%E8%AF%95%22%7D%5D'