saundy 发表于 2017-5-7 09:05:46

python中urllib.quote不支持unicode字符串

  >>> urllib.quote_plus(u'江南小财主')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/urllib.py", line 1213, in quote_plus
    return quote(s, safe)
  File "/usr/lib/python2.5/urllib.py", line 1205, in quote
    res = map(safe_map.__getitem__, s)
KeyError: u'\u6c5f'
  因为从数据库里取出来的字符串是unicode。 但是quote_plus函数只接受ascii码, 所以需要先把字符串encode一下。
  >>> urllib.quote_plus(u'江南小财主'.encode('utf8'))
'%E6%B1%9F%E5%8D%97%E5%B0%8F%E8%B4%A2%E4%B8%BB'
页: [1]
查看完整版本: python中urllib.quote不支持unicode字符串