简体   繁体   中英

Looking for a Python shorthand way of parsing a url encoded string into tuples

I have a string rssi=199&phase=-1&doppler=-1 and I am trying to parse it to look like [('rssi', '199'), ('phase', '-1'), ('doppler', '-1')] using Python.

Currently, I have a working function that does what I want. It goes like this:

s = 'rssi=199&phase=-1doppler=-1'
spl = s.split('&') # now looks like ['rssi=199', 'phase=-1', 'doppler=-1']
l = []
for i in spl:
    l.append(tuple(i.split('=')))
print l # finally have [('rssi', '199'), ('phase', '-1'), ('doppler', '-1')]

I'm looking for a shorter way to accomplish this task in fewer lines. Just to understand how I can clean up the code and for best-practice. I've seen operations in python that look like [ x.strip() for x in foo.split(";") if x.strip() ] with the for loop inside the array. I don't totally understand what that does and don't know what it is called. Any help in the right direction would be appreciated.

The structure you are asking about is called a list comprehension . You could replace your for loop with:

[v.split('=') for v in s.split('&')]

Which would give you a list like:

[['rssi', '199'], ['phase', '-1'], ['doppler', '-1']]

But for what you're doing, the urlparse.parse_qs method might be easier:

>>> import urlparse
>>> urlparse.parse_qs('rssi=199&phase=-1&doppler=-1')
{'phase': ['-1'], 'rssi': ['199'], 'doppler': ['-1']}

...or urlparse.parse_qsl , if you really want a list/tuple instead of a dict:

>>> urlparse.parse_qsl('rssi=199&phase=-1&doppler=-1')
[('rssi', '199'), ('phase', '-1'), ('doppler', '-1')]

You're looking for urlparse.parse_qsl :

>>> import urlparse
>>> urlparse.parse_qsl("foo=bar&bar=baz")
[('foo', 'bar'), ('bar', 'baz')]

It may also be helpful to turn this into a dictionary:

>>> dict(urlparse.parse_qsl("foo=bar&bar=baz"))
{'foo': 'bar', 'bar': 'baz'}

I assume that you started with a URL, split on ? and removed the host and path, and now are trying to parse the query string. You might want to use urlparse from the beginning.

import urlparse

parsed = urlparse.urlparse('http://www.bob.com/index?rssi=199&phase=-1&doppler=-1')
print parsed.hostname + parsed.path 
# www.bob.com/index

query_tuples = urlparse.parse_qsl(parsed.query)
print query_tuples 
# [('rssi', '199'), ('phase', '-1'), ('doppler', '-1')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM