python之quote报错*** KeyError: u‘\uxx‘解决
2021/9/4 20:08:50
本文主要是介绍python之quote报错*** KeyError: u‘\uxx‘解决,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
问题: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'
这篇关于python之quote报错*** KeyError: u‘\uxx‘解决的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-18初探Python股票自动化交易:入门指南
- 2024-09-18Python量化入门:轻松掌握量化分析基础与实战
- 2024-09-18Python量化交易:入门指南与实践
- 2024-09-18Python量化交易:入门指南与实战技巧
- 2024-09-14Python人工智能项目实战:从零开始的实践指南
- 2024-09-14探索Python人工智能资料:初学者的指南
- 2024-09-14Python人工智能资料:初学者的全面指南
- 2024-09-13Matplotlib入门:轻松绘制Python数据可视化图表
- 2024-09-13Python人工智能:初学者的入门指南
- 2024-09-13Python人工智能:轻松入门与实践