Reputation: 3285
Given a list of tuples for parameter names and values e.g.:
[("foo", 10), ("bar", None), ("baz", "some_string")]
and some url string e.g.:
"/some/url/string"
my function should be able to create following output string (Note that None value tuples are not included in the query string):
"/some/url/string?foo=10&baz=some_string"
I tried using join but since the values are not all strings, I would have to convert them first. Maybe someone can help me with a short and clean way of doing this.
Upvotes: 2
Views: 2115
Reputation: 11585
Just use the built-in urllib to encode the parameters for you.
>>> import urllib
>>> parameters = [("foo", 10), ("bar", None), ("baz", "some_string")]
>>> clean_parameters = [parameter for parameter in parameters if parameter[1] is not None]
>>> urllib.urlencode(clean_parameters)
'foo=10&baz=some_string'
Upvotes: 2
Reputation: 31951
>>> from urllib import urlencode
>>> data = [("foo", 10), ("bar", None), ("baz", "some_string")]
>>> urlencode(data)
'foo=10&bar=None&baz=some_string'
>>> urlencode([x for x in data if x[1] is not None]) # no None's
'foo=10&baz=some_string'
Upvotes: 5