Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to remove leading zeros from an IP address
In this tutorial, we will write a Python program to remove leading zeros from an IP address. For example, if we have an IP address 255.001.040.001, we need to convert it to 255.1.40.1.
Approach
The solution involves these steps ?
- Split the IP address by dots using
split() - Convert each part to integer (automatically removes leading zeros)
- Convert back to strings and join with dots
Example
Here's how to remove leading zeros from an IP address ?
# Initialize IP address with leading zeros
ip_address = "255.001.040.001"
# Split using the split() function
parts = ip_address.split(".")
# Convert every part to int (removes leading zeros)
parts = [int(part) for part in parts]
# Convert each to str again before joining
parts = [str(part) for part in parts]
# Join every part using the join() method
result = ".".join(parts)
print(result)
The output of the above code is ?
255.1.40.1
One-Line Solution
We can also achieve this in a single line ?
ip_address = "255.001.040.001"
result = ".".join(str(int(part)) for part in ip_address.split("."))
print(result)
255.1.40.1
Using Function
Let's create a reusable function ?
def remove_leading_zeros(ip_address):
return ".".join(str(int(part)) for part in ip_address.split("."))
# Test with different IP addresses
test_ips = ["255.001.040.001", "192.168.001.001", "010.000.000.001"]
for ip in test_ips:
cleaned_ip = remove_leading_zeros(ip)
print(f"{ip} ? {cleaned_ip}")
255.001.040.001 ? 255.1.40.1 192.168.001.001 ? 192.168.1.1 010.000.000.001 ? 10.0.0.1
How It Works
Converting a string to integer automatically removes leading zeros. For example, int("001") becomes 1. Converting back to string gives us the clean format without leading zeros.
Conclusion
Use int() conversion to remove leading zeros from IP address parts. This approach works because Python's int() function ignores leading zeros when parsing numeric strings.
