Reputation: 39
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.
Upvotes: 0
Views: 52
Reputation: 9010
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')]
Upvotes: 0
Reputation: 311693
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')]
Upvotes: 4
Reputation: 154504
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'}
Upvotes: 1