Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent urllib.parse.quote() in python 2.7

What is the equivalent of urllib.parse.quote

It's urllib.urlencode()?

Thanks

like image 721
timothylhuillier Avatar asked Feb 02 '16 09:02

timothylhuillier


People also ask

What is Urllib parse quote in Python?

parse — Parse URLs into components. This module defines a standard interface to break Uniform Resource Locator (URL) strings up in components (addressing scheme, network location, path etc.), to combine the components back into a URL string, and to convert a “relative URL” to an absolute URL given a “base URL.”

What does Urllib quote do?

The quote() function encodes space characters to %20 . If you want to encode space characters to plus sign ( + ), then you can use another function named quote_plus provided by urllib.


2 Answers

I think you are looking for urllib.pathname2url. Compare:

Python 3, urllib.parse.quote:

>>> urllib.parse.quote('abc def/foo?bar=baz')
'abc%20def/foo%3Fbar%3Dbaz'

Python 2, urllib.pathname2url:

>>> urllib.pathname2url('abc def/foo?bar=baz')
'abc%20def/foo%3Fbar%3Dbaz'

The behavior seems similar to me, but they might be subtly different.

Edit:

Reading your comment on Algina's post, I think this is my preferred way to build the url:

>>> url = 'http://dev.echonest.com/api/v4/song/search'
>>> params = {'api_key': 'xxxx', 'format': 'json', 'artist': 'Galaxie 500'}
>>> "{}?{}".format(url, urllib.urlencode(params))
'http://dev.echonest.com/api/v4/song/search?api_key=xxxx&artist=Galaxie+500&format=json'
like image 59
André Laszlo Avatar answered Oct 12 '22 15:10

André Laszlo


actually using the library six, which is made for python2/python3 compatibility you can do

import six.moves.urllib as urllib 

# and now you can use urllib as it was python3
urllib.quote(...) 

and if you just want python2, it was actually urllib.quote directly

like image 15
allan.simon Avatar answered Oct 12 '22 16:10

allan.simon