Python program to remove leading zeros from an IP address


In this tutorial, we are going to write a program which removes leading zeros from the Ip address. Let's see what is exactly is. Let's say we have an IP address 255.001.040.001, then we have to convert it into 255.1.40.1. Follow the below procedure to write the program.

  • Initialize the IP address.
  • Split the IP address with. using the split function
  • Convert each part of the IP address to int which removes the leading zeros.
  • Join all the parts by converting each piece to str.
  • The result is our final output.

Example

## initializing IP address ip_address = "255.001.040.001"
## spliting using the split() functions
parts = ip_address.split(".")
## converting every part to int
parts = [int(part) for part in parts]
## convert each to str again before joining them
parts = [str(part) for part in parts]
## joining every part using the join() method
ip_address = ".".join(parts)
print(ip_address)

If you run the above program, you will get the following result.

Output

255.1.40.1

If you have any doubts regarding the program, please do mention them in the comment section.

Updated on: 27-Aug-2019

319 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements