3

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
timkay
  • 656
  • 9
  • 15

3 Answers3

9

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')
Mark
  • 90,562
  • 7
  • 108
  • 148
2

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.

Benjamin Ye
  • 508
  • 2
  • 7
  • This one scans the data twice, and it's quite less readable. – timkay Jun 13 '21 at 18:02
  • @timkay, what do you mean it scans the data twice? If there's no "/", the IP address stored as is. Otherwise, it is split on "/". – Benjamin Ye Jun 13 '21 at 18:03
  • The "in" operation has to scan all of data. Then the "split" operation has to scan data again. – timkay Jun 13 '21 at 18:06
  • 3
    [Premature optimization is the root of all evil](http://c2.com/cgi/wiki?PrematureOptimization). Do whatever you feel is most natural and readable, and optimize it if it becomes a performance bottleneck. @timkay – Barmar Jun 13 '21 at 18:08
  • BTW, I agree with you about the readability, but that's personal opinion. – Barmar Jun 13 '21 at 18:08
2

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.

Rodrigo Rodrigues
  • 7,545
  • 1
  • 24
  • 36