I have an IP-Range 192.0.0.2-4 as string and want to split it in two new strings
ip_start = '192.0.0.2'
ip_end = '192.0.0.4'
so I have to search for "-" in "192.0.0.2-4" and split there, but how can I make the second string?
I have an IP-Range 192.0.0.2-4 as string and want to split it in two new strings
ip_start = '192.0.0.2'
ip_end = '192.0.0.4'
so I have to search for "-" in "192.0.0.2-4" and split there, but how can I make the second string?
If the range is always limited to the last byte (octet) of the address, split on the last dot of the address and replace it with your end value:
ip_start, _, end_value = iprange.partition('-')
first_three = ip_start.rpartition('.')[0]
ip_end = '{}.{}'.format(first_three, end_value)
I used str.partition() and str.rpartition() here as you only need to split just once; the methods are a little faster for that case. The methods return 3 strings, always; everything before the partition string, the partition string itself, and everything after. As we only need the first string of the . partition, I used indexing there to select it for assignment.
Since you don't need to keep that dash or dot I assigned those to a variable named _; that's just a convention and is used to signal that you'll ignore that value altogether.
Demo:
>>> iprange = '192.0.0.2-4'
>>> iprange.partition('-')
('192.0.0.2', '-', '4')
>>> iprange.partition('-')[0].rpartition('.')
('192.0.0', '.', '2')
>>> ip_start, _, end_value = iprange.partition('-')
>>> first_three = ip_start.rpartition('.')[0]
>>> ip_end = '{}.{}'.format(first_three, end_value)
>>> ip_start
'192.0.0.2'
>>> ip_end
'192.0.0.4'
For completeness sake: you can also use the str.rsplit() method to split a string from the right, but you need to include a limit in that case:
>>> first.rsplit('.', 1)
['192.0.0', '2']
Here the second argument, 1, limits the split to the first . dot found.
You could build up the second string by using the piece from the "first" IP address.
>>> def getIPsFromClassCRange(ip_range):
... # first split up the string like you did
... tmp = ip_range.split("-")
... # get the fix part of the IP address
... classC = tmp[0].rsplit(".", 1)[0]
... # append the ending IP address
... tmp[1] = "%s.%s" % (classC, tmp[1])
... # return start and end ip as a useful tuple
... return (tmp[0], tmp[1])
...
>>> getIPsFromClassCRange("192.0.0.2-4")
('192.0.0.2', '192.0.0.4')
Here is 3 steps solution, using a generator expression :
def ip_bounds(ip_string):
"""Splits ip address range like '192.0.0.2-4'
into two ip addresses : '192.0.0.2','192.0.0.4'"""
# split ip address with last '.'
ip_head, ip_tail = ip_string.rsplit('.', 1)
# split last part with '-'
ip_values = ip_tail.split('-')
# create an ip address for each value
return tuple('{}.{}'.format(ip_head,i) for i in ip_values)
ip_start, ip_end = ip_bounds('192.0.0.2-4')
assert ip_start == '192.0.0.2'
assert ip_end == '192.0.0.4'