I'm trying to get python to give me percent encoded strings. The API I'm interacting with (which I think is using percent encoded UTF-8), gives %c3%ae for î. However, python's urllib.quote gives %3F.
import urllib
mystring = "î"
print urllib.quote(mystring)
print urllib.quote_plus(mystring)
print urllib.quote(mystring.encode('utf-8'))
Any help appreciated.
Your file has to encode your string as
utf-8
before quoting it, and the string should be unicode. Also you have to specify the appropriate file encoding for your source file in thecoding
section:Gives me the output:
That is because you're not declaring the encoding your file is using, so Python is inferring it from your current
locale
configuration. I'll suggest you to do this:And also make sure your
file.py
is getting saved to disk withutf-8
encoding.For me that yields:
Couple of caveats. If your trying this from the interpreter, the
# -*- coding: utf-8 -*-
won't work if your console encoding isn'tutf-8
. Instead, you should change it to whatever encoding your console is using:# -*- coding: (encoding here) -*-
.Then, you should decode your string into
Unicode
usingdecode
method and passing it the the encoding name your console is using as argument:And later pass it to
urllib
encoded asutf-8
:Hope this helps!