extracting individual items resulting from a string split() operation
a = line.splitlines()[:2]
I got this output as shown below .
['GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1']
['Host: www.explainth.at']
['User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11']
['Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5']
['Accept-Language: en-gb,en;q=0.5']
['Accept-Encoding: gzip,deflate']
['Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7']
['Keep-Alive: 300']
I want to get the first two items:
GET /en/html/dummy.php?name=MyNam开发者_Python百科e&married=not+single &male=yes HTTP/1.1
Host: www.explainth.at
to get first 2 items.
a[:2]
The Host header field is not necessarily the first header field after the status line. So instead of getting the first two lines you should do something like this:
lines[0] + [line for line in lines[1:] if line[0][0:5].lower() == 'host:']
The list comprehension lines[0] + [line for line in lines[1:] if line[0][0:5].lower() == 'host:']
will only return the line if it starts with Host:
.
>>> a = ['GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1',
... 'Host: www.explainth.at',
... 'User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11',
... 'Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
... 'Accept-Language: en-gb,en;q=0.5',
... 'Accept-Encoding: gzip,deflate',
... 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
... 'Keep-Alive: 300']
>>> getstr=a.pop(0)
>>> adict = dict(x.partition(':')[::2] for x in a)
>>> adict['Host']
' www.explainth.at'
精彩评论