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
    评论
Python 爬虫正则表达式是非常常用的技术,可以帮助我们从网页提取出需要的信息。下面是一些常用的正则表达式符号和方法: 1. ".":匹配任意单个字符,除了换行符。 2. "^":匹配字符串的开始位置。 3. "$":匹配字符串的结束位置。 4. "*":匹配前一个字符出现 0 次或多次。 5. "+":匹配前一个字符出现 1 次或多次。 6. "?":匹配前一个字符出现 0 次或 1 次。 7. "{m}":匹配前一个字符出现 m 次。 8. "{m,n}":匹配前一个字符出现 m 到 n 次。 9. "(...)":分组匹配,匹配括号内的表达式。 10. "[...]":匹配括号内的任意一个字符。 11. "[^...]":匹配不在括号内的任意一个字符。 12. "\d":匹配数字,等同于 [0-9]。 13. "\D":匹配非数字,等同于 [^0-9]。 14. "\s":匹配空白字符,包括空格、制表符、换行符等。 15. "\S":匹配非空白字符。 16. "\w":匹配单词字符,包括字母、数字、下划线。 17. "\W":匹配非单词字符。 在 Python ,使用 re 模块进行正则表达式的匹配。常用的方法包括: 1. re.compile(pattern):将正则表达式编译成一个对象,提高匹配效率。 2. re.search(pattern, string):在字符串搜索匹配正则表达式的第一个位置。 3. re.findall(pattern, string):在字符串搜索匹配正则表达式的所有位置,并返回一个列表。 4. re.sub(pattern, repl, string):将字符串所有匹配正则表达式的字符替换为指定的字符串。 以上是一些常用的正则表达式符号和方法,希望能对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值