使用Python删除IP地址中的前导零 [英] Remove leading zeros in IP address using Python

查看:357
本文介绍了使用Python删除IP地址中的前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

删除IP地址中不必要的零:

Remove unnecessary zeros in IP address:

100.020.003.400  ->  100.20.3.400
001.200.000.004  ->  1.200.0.4
000.002.300.000  ->  0.2.300.0   (optional silly test)

我的尝试并非在所有情况下都有效:

My attempt does not work well in all cases:

import re
ip = re.sub('[.]0+', '.', ip_with_zeroes)

有类似的问题,但对于其他语言:

There are similar question but for other languages:

  • Perl
  • SQL

请同时提供适用于Python v2和v3的解决方案.

Please provide solutions for both Python v2 and v3.

推荐答案

使用 netaddr库,然后显示ZEROFILL标志:

import netaddr

ip = "055.023.156.008"

no_zero_ip = netaddr.IPAddress(ip, flags=netaddr.ZEROFILL).ipv4()

# IPAddress('55.23.156.8')

如果您不希望IPAddress类型,则可能要将no_zero_ip结果更改为字符串或其他内容.

You probably want to change the no_zero_ip result to a string or something else if you don't want the IPAddress type

这篇关于使用Python删除IP地址中的前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆