Print line containing “word” python

后端 未结 2 1015
礼貌的吻别
礼貌的吻别 2021-01-19 06:17

I would like to print ONLY the line which contains \"Server\" in the below piece of output:

Date: Sun, 16 Dec 2012 20:07:44 GMT
Expires: -1
Cache-Control: pr         


        
相关标签:
2条回答
  • 2021-01-19 06:58
    for single_line in websiteheaders.splitlines():
        if `Server` in single_line:
            print single_line
    
    0 讨论(0)
  • 2021-01-19 07:09

    Is websiteheaders really a list which is split for very line? Because if it's a string you should use:

    for line in websiteheaders.splitlines():
        if "Server" in line:
            print line
    

    Also, a good tip: I would recommend adding some print-statements on encountering this kind of problems. If you would have added something like:

    else:
        print 'WRONG LINE:', line
    

    You probably would have catched that this loop was not looping over every line but over every character.

    Update

    I can't wee what's wrong with your code then. This is what I get:

    In [3]: websiteheaders
    Out[3]: 
    ['Date: Sun, 16 Dec 2012 20:07:44 GMT',
     'Expires: -1',
     'Cache-Control: private, max-age=0',
     'Content-Type: text/html; charset=ISO-8859-1',
     'Set-Cookie: PREF=ID=da8d52b67e5c7522:FF=0:TM=1355688464:LM=1355688464:S=CrK5vV-qb3UgWUM1; expires=Tue, 16-Dec-2014 20:07:44 GMT; path=/; domain=.google.com',
     'Set-Cookie: NID=67=nICkwXDM6H7TNQfHbo06FbvZhO61bzNmtOn4HA71ukaVDSgywlBjBkAR-gXCpMNo1TlYym-eYMUlMkCHVpj7bDRwiHT6jkr7z4dMrApDuTk_HuTrZrkoctKlS7lXjz9a; expires=Mon, 17-Jun-2013 20:07:44 GMT; path=/; domain=.google.com; HttpOnly',
     'P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."',
     'Server: gws',
     'X-XSS-Protection: 1; mode=block',
     'X-Frame-Options: SAMEORIGIN',
     'Connection: close"']
    
    In [4]: for line in websiteheaders:
       ...:     if 'Server' in line:
       ...:         print line
       ...:         
    Server: gws
    
    0 讨论(0)
提交回复
热议问题