Q:

Python Regex | program to Remove leading zeros from an IP address

0

Given an IP address as input, write a Python program to remove leading zeros from it.

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 using sub() method of "re" module.

Syntax:

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

The sub() in the function stands for SubString, a certain regular expression pattern is searched in the given string(3rd parameter), and upon finding the substring pattern is replaced by repl(2nd parameter), count checks and maintains the number of times this occurs.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now