def _oauth_escape(val):
if isinstance(val, unicode):# useful ?
val = val.encode("utf-8")#useful ?
return urllib.quote(val, safe="~")
我觉得没用
是的 ??
更新
我认为unicode是'utf-8',是吗?
utf-8 是一种编码,是一种将 unicode 数据具体表示为一系列字节的方法。这是许多这样的编码之一。Pythonstr
对象是字节串,可以表示任意二进制数据,例如特定编码的文本。
Python 的 unicode 类型是一种抽象的、未编码的方式来表示文本。unicode 字符串可以用多种编码中的任何一种进行编码。
正如其他人已经说过的那样,unicode 和 utf-8 是不一样的。Utf-8 是 unicode 的众多编码之一。
将unicode
对象视为“未编码”的 unicode 字符串,而string
对象以特定编码进行编码(不幸的是,字符串对象没有告诉您它们是如何编码的属性)。
val.encode("utf-8")
将此 unicode 对象转换为 utf-8 编码的字符串对象。
在 Python 2.6 中,这是必要的,因为urllib
无法正确处理 unicode。
>>> import urllib
>>> urllib.quote(u"")
''
>>> urllib.quote(u"ä")
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib.py:1216: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
res = map(safe_map.__getitem__, s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib.py", line 1216, in quote
res = map(safe_map.__getitem__, s)
KeyError: u'\xe4'
>>> urllib.quote(u"ä".encode("utf-8"))
'%C3%A4'
然而,在 Python 3.x 中,所有字符串都是 unicode(Python 3 等价于编码字符串是一个bytes
对象),不再需要它了。
>>> import urllib.parse
>>> urllib.parse.quote("ä")
'%C3%A4'
在 Python 3.0 中,所有字符串都支持 Unicode,但在以前的版本中,必须将字符串显式编码为 Unicode 字符串。会是这样吗?
(utf-8 不是唯一的,而是最常见的 Unicode 编码。阅读此。)