How to decode url to path in python, django

15,447

Solution 1

Use urllib.unquote to decode %-encoded string:

>>> import urllib
>>> url = u'/static/media/uploads/gallery/Marrakech%2C%20Morocco_be3Ij2N.jpg'
>>> urllib.unquote(url)
u'/static/media/uploads/gallery/Marrakech, Morocco_be3Ij2N.jpg'

Using urllib.quote or urllib.quote_plus, you can get back:

>>> urllib.quote(u'/static/media/uploads/gallery/Marrakech, Morocco_be3Ij2N.jpg')
'/static/media/uploads/gallery/Marrakech%2C%20Morocco_be3Ij2N.jpg'

Solution 2

If you are using Python3 you can write

urllib.parse.unquote(url)
Share:
15,447

Related videos on Youtube

k.rozycki
Author by

k.rozycki

Updated on June 19, 2022

Comments

  • k.rozycki
    k.rozycki almost 2 years

    Hi I need to convert url to path, what i got is this url as bellow:

    url = u'/static/media/uploads/gallery/Marrakech%2C%20Morocco_be3Ij2N.jpg'
    

    and what to be looked something like this:

    path = u'/static/media/uploads/gallery/Marrakech, Morocco_be3Ij2N.jpg'
    

    thx.

  • Humphrey
    Humphrey about 8 years
    Note that in Python 3 this is in the module urllib.parse.
  • falsetru
    falsetru about 8 years
    @Humphrey, The question is tagged python-2.7.