简体   繁体   English

缩写IPv6地址

[英]Abbreviating IPv6 addresses

There is an array with IP addresses. 有一个带有IP地址的阵列。 I need a selected IP address to shorten. 我需要一个选定的IP地址来缩短。 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 eg 0000 need to change it to 0 . 缩写规则:如果从0开始的零件需要从零件中删除,或者存在例如0000需要将其更改为0 The previous example after abbreviation: 缩写后的上一个示例:

['fcef:b0e7:7d20:0:0:0:3b95:565']

You can use a generator expression within join as following : 您可以在join使用生成器表达式,如下所示:

>>> ':'.join('0' if i.count('0')==4 else i.lstrip('0') for i in s.split(':'))
'fcef:b0e7:7d20:0:0:0:3b95:565'

or as @JF Sebastian mentioned in comment you can just use i == '0000' instead of count ! 或正如评论中提到的@JF Sebastian一样,您可以只使用i == '0000'代替count

>>> ':'.join('0' if i=='0000' else i.lstrip('0') for i in s.split(':'))
'fcef:b0e7:7d20:0:0:0:3b95:565'

You should use the ipaddress module from the standard library: 您应该使用标准库中的ipaddress模块:

>>> 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. 这会根据实际规则缩短IP。

To shorten the ip with only the rule you cite, you can simply use replace : 要仅使用您引用的规则来缩短ip,您可以简单地使用replace

>>> 'fcef:b0e7:7d20:0000:0000:0000:3b95:0565'.replace('0000', '0')
'fcef:b0e7:7d20:0:0:0:3b95:0565'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM