I am struggling to convert a url to a nested tuple.
# Convert this string
str = 'http://somesite.com/?foo=bar&key=val'
# to a tuple like this:
[(u'foo', u'bar'), (u'key', u'val')]
I assume I need to be doing something like:
url = 'http://somesite.com/?foo=bar&key=val'
url = url.split('?')
get = ()
for param in url[1].split('&'):
get = get + param.split('=')
What am I doing wrong? Thanks!
When it is required to convert a string into a tuple, the 'map' method, the 'tuple' method, the 'int' method, and the 'split' method can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.
Method #1 : Using map() + int + split() + tuple() This method can be used to solve this particular task. In this, we just split each element of string and convert to list and then we convert the list to resultant tuple.
Method #1: Using list comprehension + join() The list comprehension performs the task of iterating the entire list of tuples and the join function performs the task of aggregating the elements of tuples into one list.
Inbuilt tuple() function, also known as a constructor function, can be used to convert a list to a tuple. We can use for loop inside the tuple function to convert the list into a tuple. It is faster to convert the list to a tuple in python by unpacking the list inside parenthesis.
I believe you are looking for the urlparse
module.
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.”
Here is an example:
from urlparse import urlparse, parse_qsl
url = 'http://somesite.com/?foo=bar&key=val'
print parse_qsl(urlparse(url)[4])
Output:
[('foo', 'bar'), ('key', 'val')]
In this example I first use the urlparse
function to parse the entire URL then I use the parse_qsl
function to break the querystring (the fifth element returned from urlparse
) into a list of tuples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With