Python如何从IP地址中删除前导零()

给定IP地址, 请从IP地址中删除前导零。
例子:

Input : 100.020.003.400 Output : 100.20.3.400Input :001.200.001.004 Output : 1.200.1.4

方法1:遍历和加入
的方法是将给定的字符串除以” .” 然后将其转换为可删除前导零的整数, 然后将其重新连接为字符串。要将字符串转换为整数, 我们可以使用整数然后将其转换回字符串力量然后使用join函数将它们重新加入。
# Python program to remove leading zeros # an IP address and print the IP# function to remove leading zeros def removeZeros(ip):# splits the ip by "." # converts the words to integeres to remove leading removeZeros # convert back the integer to string and join them back to a string new_ip = "." .join([ str ( int (i)) for i in ip.split( "." )]) return new_ip ; # driver code # example1 ip = "100.020.003.400" print (removeZeros(ip))# example2 ip = "001.200.001.004" print (removeZeros(ip))

输出如下:
100.20.3.400 1.200.1.4

方法2:正则表达式
使用捕获组, 匹配最后一位并复制它, 并防止所有数字被替换。
正则表达式\ d可以解释为:
\ d:
匹配任何十进制数字
\dMatches any decimal digit, this is equivalent to the set class [0-9].

\ b允许你使用\ bword \ b形式的正则表达式执行” 仅全词” 搜索
正则表达式\ b可以解释为:
\b allows you to perform a "whole words only" search u sing a regular expression in the form of \bword\b

# Python program to remove leading zeros # an IP address and print the IP using regex import re # function to remove leading zeros def removeZeros(ip): new_ip = re.sub(r '\b0+(\d)' , r '\1' , ip) # splits the ip by "." # converts the words to integeres to remove leading removeZeros # convert back the integer to string and join them back to a stringreturn new_ip # driver code # example1 ip = "100.020.003.400" print (removeZeros(ip))# example2 ip = "001.200.001.004" print (removeZeros(ip))

输出如下:
100.20.3.400 1.200.1.4

【Python如何从IP地址中删除前导零()】首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

    推荐阅读