Url decode UTF-8 in Python Url decode UTF-8 in Python python python

Url decode UTF-8 in Python


The data is UTF-8 encoded bytes escaped with URL quoting, so you want to decode, with urllib.parse.unquote(), which handles decoding from percent-encoded data to UTF-8 bytes and then to text, transparently:

from urllib.parse import unquoteurl = unquote(url)

Demo:

>>> from urllib.parse import unquote>>> url = 'example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0'>>> unquote(url)'example.com?title=правовая+защита'

The Python 2 equivalent is urllib.unquote(), but this returns a bytestring, so you'd have to decode manually:

from urllib import unquoteurl = unquote(url).decode('utf8')


If you are using Python 3, you can use urllib.parse

url = """example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0"""import urllib.parseurllib.parse.unquote(url)

gives:

'example.com?title=правовая+защита'


You can achieve an expected result with requests library as well:

import requestsurl = "http://www.mywebsite.org/Data%20Set.zip"print(f"Before: {url}")print(f"After:  {requests.utils.unquote(url)}")

Output:

$ python3 test_url_unquote.pyBefore: http://www.mywebsite.org/Data%20Set.zipAfter:  http://www.mywebsite.org/Data Set.zip

Might be handy if you are already using requests, without using another library for this job.