There is an array with IP addresses. I need a selected IP address to shorten. For example:
['fcef:b0e7:7d20:0000:0000:0000:3b95:0565']
abbreviation rules: if a part beginning 0 need to del from part or there is e.g. 0000
need to change it to 0
.
The previous example after abbreviation:
['fcef:b0e7:7d20:0:0:0:3b95:565']
You should use the ipaddress
module from the standard library:
>>> import ipaddress
>>> str(ipaddress.ip_address('fcef:b0e7:7d20:0000:0000:0000:3b95:0565'))
'fcef:b0e7:7d20::3b95:565'
>>> ip = ipaddress.ip_address('fcef:b0e7:7d20:0000:0000:0000:3b95:0565')
>>> ip.compressed
'fcef:b0e7:7d20::3b95:565'
>>> ip.exploded
'fcef:b0e7:7d20:0000:0000:0000:3b95:0565'
This shortens the ip under the actual rules.
To shorten the ip with only the rule you cite, you can simply use replace
:
>>> 'fcef:b0e7:7d20:0000:0000:0000:3b95:0565'.replace('0000', '0')
'fcef:b0e7:7d20:0:0:0:3b95:0565'