UTF-8百分比编码和python

use*_*351 4 python utf-8 url-encoding

我试图让python给我百分比编码的字符串.我正在与之交互的API(我认为使用百分比编码的UTF-8)给出了%c3%ae.但是,python的urllib.quote给出%3F.

import urllib

mystring = "î"
print urllib.quote(mystring)
print urllib.quote_plus(mystring)
print urllib.quote(mystring.encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

任何帮助赞赏.

Vik*_*kez 6

您的文件必须utf-8在引用之前对您的字符串进行编码,字符串应为unicode.您还必须在以下coding部分中为源文件指定适当的文件编码:

# -*- coding: utf-8 -*-

import urllib

s = u'î'
print urllib.quote(s.encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

给我输出:

%C3%AE
Run Code Online (Sandbox Code Playgroud)

  • 请注意,在Python3中,这将是`import urllib.parse`,然后是`urllib.parse.quote`. (2认同)