提取字符串split()操作产生的单个项目

时间:2010-09-13 10:11:10

标签: python

a = line.splitlines()[:2]

我得到了这个输出,如下所示。

['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']

我想获得前两项:

GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1
Host: www.explainth.at

3 个答案:

答案 0 :(得分:1)

获得前2项。

a[:2]

答案 1 :(得分:1)

主机标头字段不一定是状态行之后的第一个标头字段。因此,不应该获得前两行,而应该执行以下操作:

lines[0] + [line for line in lines[1:] if line[0][0:5].lower() == 'host:']

列表理解lines[0] + [line for line in lines[1:] if line[0][0:5].lower() == 'host:']只会在以Host:开头时返回该行。

答案 2 :(得分:0)

>>> 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'