kun
kun

Reputation: 4217

pythonic way to extract string from this list

if I have a list ['default via 192.168.0.1 dev wlan0 proto static \n', '192.168.0.0/24 dev wlan0 proto kernel scope link src 192.168.0.11 \n'] what will be the most pythonic way to extract 192.168.0.1 and 192.168.0.11 out of it

Upvotes: 3

Views: 108

Answers (2)

Óscar López
Óscar López

Reputation: 235984

Try this using regular expressions, where lst is the list with the data:

import re
pat = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}[^/]')
[pat.search(s).group(0) for s in lst]
=> ['192.168.0.1', '192.168.0.11']

The above assumes that there's a valid IPv4 IP in each string in the list, and that after the IP there isn't a / character.

Upvotes: 4

Fred Osterrath
Fred Osterrath

Reputation: 131

«Most pythonic» might be debatable, but something along these lines will work :

fct = lambda e : [w for w in e.split() if '.' in w and '/' not in w][0]
map( fct, l )

> ['192.168.0.1', '192.168.0.11']

Upvotes: 3

Related Questions