我在 python 代码中有一个 unicode 字符串:
name = u'Mayte_Martín'
我想将它与 SPARQL 查询一起使用,这意味着我应该使用“utf-8”对字符串进行编码,并在其上使用 urllib.quote_plus 或 requests.quote。然而,这两个引用函数的行为都很奇怪,无论是否使用“安全”参数都可以看出这一点。
from urllib import quote_plus
没有“安全”参数:
quote_plus(name.encode('utf-8'))
Output: 'Mayte_Mart%C3%ADn'
使用“安全”参数:
quote_plus(name.encode('utf-8'), safe=':/')
Output:
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-164-556248391ee1> in <module>()
----> 1 quote_plus(v, safe=':/')
/usr/lib/python2.7/urllib.pyc in quote_plus(s, safe)
1273 s = quote(s, safe + ' ')
1274 return s.replace(' ', '+')
-> 1275 return quote(s, safe)
1276
1277 def urlencode(query, doseq=0):
/usr/lib/python2.7/urllib.pyc in quote(s, safe)
1264 safe = always_safe + safe
1265 _safe_quoters[cachekey] = (quoter, safe)
-> 1266 if not s.rstrip(safe):
1267 return s
1268 return ''.join(map(quoter, s))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 10: ordinal not in range(128)
问题似乎出在 rstrip 函数上。我尝试进行一些更改并调用...
quote_plus(name.encode('utf-8'), safe=u':/'.encode('utf-8'))
但这并没有解决问题。这可能是什么问题?
最佳答案
我正在回答我自己的问题,以便它可以帮助面临同样问题的其他人。
当您在执行任何其他操作之前在当前工作区中进行以下导入时,会出现此特定问题。
from __future__ import unicode_literals
这不知何故与以下代码序列不兼容。
from urllib import quote_plus
name = u'Mayte_Martín'
quote_plus(name.encode('utf-8'), safe=':/')
没有导入 unicode_literals 的相同代码工作正常。
关于python - 在带有 'safe' 参数的 utf-8 字符串上使用 python 的 urllib.quote_plus,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22415345/