那是因为你没有声明你的文件使用的编码,所以 Python 是从你当前的locale配置中推断出来的。我会建议你这样做:
# -*- coding: utf-8 -*-
import urllib
mystring = "î"
print urllib.quote(mystring)
print urllib.quote_plus(mystring)
并确保您file.py使用utf-8encoding保存到磁盘。
对我来说,这会产生:
$python ex.py
%C3%AE
%C3%AE
几个警告。如果您从解释器尝试此操作,则# -*- coding: utf-8 -*-如果您的控制台编码不是utf-8. 相反,您应该将其更改为您的控制台使用的任何编码:# -*- coding: (encoding here) -*-.
然后,您应该将您的字符串解码为Unicodeusingdecode方法,并将控制台使用的编码名称作为参数传递给它:
mystring = "î".decode('<your encoding>')
然后将其传递给urllib编码为utf-8:
print urllib.quote(mystring.encode('utf-8'))
print urllib.quote_plus(mystring.encode('utf-8'))
希望这可以帮助!