3

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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This code doesn't give OP the answer he was looking for. "to extract 192.168.0.1 and 192.168.0.11 out of it"
@OmnipotentEntity there you go!
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.