python 补前导零_Python正则表达式| 程序从IP地址中删除前导零

python 补前导零

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

给定一个IP地址作为输入,编写一个Python程序以从中删除前导零。

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.

在此程序中,我们使用“ re”模块的 sub()方法

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.

在功能子()代表子串,一个特定正则表达式模式中搜索给定的字符串( 第三参数)中,并在找到的子图案由REPL(第2参数)代替,计数检查和维护数这种情况经常发生。

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 


翻译自: https://www.includehelp.com/python/python-regex-program-to-remove-leading-zeros-from-an-ip-address.aspx

python 补前导零

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值