Remove leading zeros in IP address using Python

Viewed 2926

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.

6 Answers

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

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.

Related