Home » Python » Python programs

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

Python Regex example: Here, we are going to learn how to remove leading zeros from an IP address using Python program?
Submitted by Ankit Rai, on June 05, 2019

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.

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 





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.