Python移除子网计算程序输出中的括号与引号问题求助
解决Python子网输出中括号和引号的问题
嘿,我懂你的困扰——你现在直接打印的是octet这个列表对象,Python默认会把列表以带方括号和元素引号的格式输出,这就是那些多余符号出现的原因啦。
要搞定这个很简单,只需要把列表里的四个字符串元素用.连接成标准的IP格式字符串就行,用Python的str.join()方法就能轻松实现。
修改后的完整代码
networkAddress = raw_input('Enter network address: ') n = input('Enter number of network bits: ') h = 32 - n hostAddressOut = 2 ** h hostAddress = 0 x = input('Enter number of subnets: ') octet = networkAddress.split('.') for i in range(x): if hostAddress > 255: hostAddress = 0 thirdOctet = int(octet[2]) + 1 octet[2] = str(thirdOctet) octet[3] = str(hostAddress) # 将列表转为标准IP字符串输出 print 'subnet', i, ' = ', '.'.join(octet) hostAddress = hostAddressOut else: octet[3] = str(hostAddress) # 同样处理此处输出 print 'subnet', i, ' = ', '.'.join(octet) hostAddress = hostAddress + hostAddressOut
原理说明
'.'.join(octet)会遍历octet列表里的每一个字符串元素,把它们用.拼接起来。比如原来的['192', '168', '1', '0']就会变成'192.168.1.0',这样打印出来就是正常的子网地址格式,再也不会出现括号和引号了。
另外提个小细节,你的代码是基于Python 2的(用了raw_input和不带括号的print),如果之后要迁移到Python 3,记得把raw_input改成input,给print加上括号哦。
内容的提问来源于stack exchange,提问作者Mark Joseph Balagtas
相关产品推荐
相关产品推荐

