Get value from query string in Python 3 without the [' '] showing up in the value

Viewed 1141

I have the following code in a Python 3 http server parse out a URL and then parse out a query string:

parsedURL = urlparse(self.path)
parsed = parse_qs(parsedURL.query)

say that parsedURL.query in this case turns about to be x=7&=3.I want to get the 7 and the 3 out and set them equal to variables x and y. I've tried both

x = parsed['x']
y = parsed['y']

and

x = parsed.get('x')
y = parsed.get('y')

both of these solutions come up with x = ['7'] and y = ['3'] but I don't want the brackets and single quotes, I want just the values 7 and 3, and I want them to be integers. How do I get the values out and get rid of the brackets/quotes?

1 Answers

Would simply:

x = int(parsed['x'][0])
y = int(parsed['y'][0])

or

x = int(parsed.get('x')[0])
y = int(parsed.get('y')[0])

serve your purpose? You should of course have suitable validation checks, but all you want to do is convert the first element of the returned array to an int, so this code will do the business.

This is because the get() returns an array of values (I presume!) so if you try parsing url?x=1&x=2&x=foo you would get back a list like ['1', '2', 'foo']. Normally there is only one (or zero, of course) instance of each variable in a query string, so we just grab the first entry with [0].

Note the documentation for parse_qs() says:

Data are returned as a dictionary. The dictionary keys are the unique query variable names and the values are lists of values for each name.

Related