Python Regex program to Remove leading zeros from an IP address

Python Regex program to Remove leading zeros from an IP address

Python Regex model: Here, we will figure out how to expel driving zeros from an IP address utilizing Python program?

Given an IP address as information, compose a Python program to expel driving zeros from it.

Models/Examples:

    Input:  216.08.094.196
    Output: 216.8.94.196

    Input: 216.08.004.096
    Output: 216.8.4.96

In this program, we are utilizing the sub() method of “re” module.

Language structure:

    re.sub(pattern, repl, string, count=0, flags=0)

The sub() in the capacity represents SubString, a specific normal articulation design is looked in the given string(3rd parameter), and after finding the substring design is supplanted by repl(2nd parameter), tally checks and keeps up the occasions this happens.

Code:

# Python program to Remove leading zeros from an IP address

# import re module

# re module provides support
# for regular expressions
import re

# Make a regular expression for 
# finding leading zeros in ip address
regex = '\.[0]*'
	
# Define a function for Remove
# leading zeros from an IP address
def removeLeadingZeros(ip):

    modified_ip = re.sub(regex, '.', ip)

    print(modified_ip)


# Main code 
if __name__ == '__main__' : 
	
	# Enter ip address 
	ip = "216.08.094.196"
	
	# call function 
	removeLeadingZeros(ip)

	ip = "216.08.004.096"

	removeLeadingZeros(ip)

Output:

216.8.94.196
216.8.4.96

Recent Posts

error: Alert: Content is protected!!