Remove leading zeros in IP address with Python
Remove unnecessary zeros in the 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 doesn't work well in all cases:
import re
ip = re.sub('[.]0+', '.', ip_with_zeroes)
There is a similar question, but for other languages:
Please provide solutions for both Python v2 and v3.
source to share
Use the netaddr library and then it has a flag ZEROFILL
:
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 result no_zero_ip
to string or whatever if you don't want the typeIPAddress
source to share
Prior to 2.6, you can use the string-modulo operator. But let me not talk about it.
This needs to be done as format
method (2.6):
'.'.join('{0}'.format(int(i)) for i in ip.split('.'))
Optionally exclude index for python ≥3.3 or ≥2.7 (I think):
'.'.join('{}'.format(int(i)) for i in ip.split('.'))
And only for python ≥3.6 we get an f-string:
'.'.join(f'{int(i)}' for i in ip.split('.'))
If you can use the latter, I highly recommend it. This is quite satisfactory.
source to share
The easiest way to do it in Python 3.3+ is to use the built-in module ipaddress
import ipaddress
print(str(ipaddress.ip_address("127.000.000.1")))
will print out
127.0.0.1
But please note that you will receive an ValueError
invalid IP address exception . The good part is that this also works with IPv6 addresses.
source to share