想获得IP地址递增的字符串
用Python2,风平浪静
$ cat python2_ip.py
for i in range(10):
print '11.0.{0}.{1}/32'.format(i/256,i%256)
$
$ python python2_ip.py
11.0.0.0/32
11.0.0.1/32
11.0.0.2/32
11.0.0.3/32
11.0.0.4/32
11.0.0.5/32
11.0.0.6/32
11.0.0.7/32
11.0.0.8/32
11.0.0.9/32
换成Python3,怎么出这种结果了?
$ cat python3_ip.py
for i in range(10):
print('11.0.{0}.{1}/32'.format(i/256,i%256))
$
$ python3 python3_ip.py
11.0.0.0.0/32
11.0.0.00390625.1/32
11.0.0.0078125.2/32
11.0.0.01171875.3/32
11.0.0.015625.4/32
11.0.0.01953125.5/32
11.0.0.0234375.6/32
11.0.0.02734375.7/32
11.0.0.03125.8/32
11.0.0.03515625.9/32
问题出在i/256!
在python2中,"整数/整数"得到的是商;
在python3中,"整数/整数"得到的是精确值
,"整数//整数"得到的是商,注意是两个//
$ cat python3_ip.py
for i in range(10):
print('11.0.{0}.{1}/32'.format(i/256,i%256))
$
$ python3 python3_ip.py
11.0.0.0/32
11.0.0.1/32
11.0.0.2/32
11.0.0.3/32
11.0.0.4/32
11.0.0.5/32
11.0.0.6/32
11.0.0.7/32
11.0.0.8/32
11.0.0.9/32