简体   繁体   中英

Remove leading zeros in IP address using Python

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:

Please provide solutions for both Python v2 and v3.

ip = "100.020.003.400"
print '.'.join(str(int(part)) for part in ip.split('.'))
# 100.20.3.400

Use the netaddr library and then it has the ZEROFILL flag:

import netaddr

ip = "055.023.156.008"

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

# IPAddress('55.23.156.8')

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

For prior to 2.6 you can use the string-modulo operator. But let's not talk about that.

This should do it as far back as the format method was introduced (2.6):

'.'.join('{0}'.format(int(i)) for i in ip.split('.'))

Optionally eliminate the index the for python ≥3.3 or ≥2.7 (I think):

'.'.join('{}'.format(int(i)) for i in ip.split('.'))

And for python ≥3.6 only, we get to f-string it up:

'.'.join(f'{int(i)}' for i in ip.split('.'))

If you can use the last, I highly recommend it. It's quite satisfying.

使用捕获组匹配最后一个数字并复制它,以防止替换所有数字。

ip = re.sub(r'\b0+(\d)', r'\1', ip_with_zeroes)

You can split by "." convert to integer and then string, and join by "."

ip = ".".join([str(int(i)) for i in ip.split(".")])

The Easiest way to do this on Python 3.3+ is to use built-in ipaddress module

import ipaddress
print(str(ipaddress.ip_address("127.000.000.1")))

will print

127.0.0.1

But note that, you'll get an ValueError exception on invalid IP addresses. The good part is this also works with IPv6 addresses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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