Search code examples
pythonpython-2.7python-3.xip-addressleading-zero

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.


Solution

  • 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