Python将IP转换为八进制地址

问题描述 投票:1回答:3

如何在python 2.7中将IP地址转换为虚线八进制地址?像这样的例子':127.0.0.1 = 0177.0000.0000.0001'

我试过这个,但给我不同的结果

ip = '127.0.0.1'
print '.'.join([oct(int(x)+256)[3:] for x in ip.split('.')])
python python-2.7 ip converter octal
3个回答
1
投票

试试这个:

[编辑:感谢abarnert指出一种更简单的使用格式的方式]

>>> ip = '127.0.0.1'
>>> print '.'.join(format(int(x), '04o') for x in ip.split('.'))
0177.0000.0000.0001

1
投票

试试这个:

print '%04o.%04o.%04o.%04o' % tuple(map(int, ip.split('.')))

0
投票

试试这个:

ip="127.0.0.1"
octalIP='.'.join(["%04o" % int(x) for x in ip.split('.')])
print octalIP

输出:0177.0000.0000.0001

© www.soinside.com 2019 - 2024. All rights reserved.