Python one liner to split string such as "192.168.0.0/24" and "8.8.8.8"?

Viewed 78

In Perl or Javascript, it's a one-liner:

my($net, $bits) = split('/', $data, 2);

or

let [net, bits] = data.split('/');

Is there a one-liner in Python? As far as I can tell, it takes several lines. For example:

res = data.split('/')
ip, bits = res[0], None
if len(res) == 2:
    bits = res[1]

or, better,

res = data.split('/')
ip, bits = res if len(res) == 2 else res[0], None
3 Answers

You can use partition() for this if you don't mind the slight ugliness of an unused variable:

net, _, bits = "8.8.8.8".partition('/')
net, bits
# ('8.8.8.8', '')

net, _, bits = "192.168.0.0/24".partition('/')
net, bits
# ('192.168.0.0', '24')

You could use list unpacking when / is in the IP address:

ip, bits = data.split('/') if '/' in data else data, None

The ternary operator accounts for when you don't have bits information, in which case bits = None.

The simplest approach would be:

ip, *bits = data.split('/')

his avoid the not enough values to unpack problem. Just remember that bits, if exists, will be inside a list.

Related