本文共 1342 字,大约阅读时间需要 4 分钟。
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 expressionsimport re# Make a regular expression for # finding leading zeros in ip addressregex = '\.[0]*' # Define a function for Remove# leading zeros from an IP addressdef 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.196216.8.4.96
翻译自:
python 补前导零
转载地址:http://hzxzd.baihongyu.com/