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

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

例子:

Input : 100.020.003.400 
Output : 100.20.3.400

Input :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:

匹配任何十进制数字

\d   Matches 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 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

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


来源:

https://www.srcmini02.com/70077.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_39548.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?