Search code examples
pythonpython-2.7urllib

Encoding / for a URL


I'm trying to encode a / for a URL using urllib.quote. Following the documentation I'm passing an empty string for the second parameter to ensure / is not excluded from being encoded:

print(quote('prøve med / i den', ''))

However, I'm getting the following error:

File "/path/to/my/file.py", line 388, in my_function

print(quote('prøve med / i den', ''))

File "/usr/local/lib/python2.7/urllib.py", line 1298, in quote

return ''.join(map(quoter, s))

KeyError: u'\xf8'


Solution

  • Try using a unicode string:

    u'prøve med / i den'
    

    Instead of:

    'prøve med / i den'
    

    KeyError: u'\xf8'

    It is the hex code for ø.