# Python如何从IP地址中删除前导零？

``````Input : 100.020.003.400
Output : 100.20.3.400

Input :001.200.001.004
Output : 1.200.1.4``````

``````# 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``````

\ d：

``````\d   Matches any decimal digit, this is equivalent
to the set class [0-9].``````

\ b允许你使用\ bword \ 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 string

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``````

• 回顶