How to find text in a column with Python

advertisements

If I had the text below in a variable, what is the best way to be able to search with say "NetName:" and get "LVLT-GOGL-8-8-8" returned?

NetRange:       8.8.8.0 - 8.8.8.255

CIDR:           8.8.8.0/24

NetName:        LVLT-GOGL-8-8-8

NetHandle:      NET-8-8-8-0-1

Parent:         LVLT-ORG-8-8 (NET-8-0-0-0-1)

NetType:        Reallocated

NetType:        Reallocated

OriginAS:  

Organization:   Google Inc. (GOGL)

RegDate:        2014-03-14

Updated:        2014-03-14

Ref:            http://whois.arin.net/rest/net/NET-8-8-8-0-1


You can use regex,in this case re.search could does the job :

>>> s="""NetRange:       8.8.8.0 - 8.8.8.255
...
... CIDR:           8.8.8.0/24
...
... NetName:        LVLT-GOGL-8-8-8
...
... NetHandle:      NET-8-8-8-0-1
...
... Parent:         LVLT-ORG-8-8 (NET-8-0-0-0-1)
...
... NetType:        Reallocated
...
... NetType:        Reallocated
...
... OriginAS:
...
... Organization:   Google Inc. (GOGL)
...
... RegDate:        2014-03-14
...
... Updated:        2014-03-14
...
... Ref:            http://whois.arin.net/rest/net/NET-8-8-8-0-1"""
>>> import re

>>> re.search(r'NetName:\s+(.*)',s).group(1)
'LVLT-GOGL-8-8-8'

Or you can loop over the splitted string and use a generator expression :

>>> next(line.split()[-1] for line in s.split('\n') if 'NetName:' in line)
'LVLT-GOGL-8-8-8'