Home  >  Q&A  >  body text

python - Solving IP segmentation problem

There is such an ip: "192.168.1.1-5,192.168.1.10-15"
I want it to be output as:
192.168.1.1
192.168.1.2
192.168.1.3
What's there? Is it a good idea? I can use text processing in Yi Language to implement this. I’m not very familiar with Python yet, so I’d like to ask someone to give me some ideas.

曾经蜡笔没有小新曾经蜡笔没有小新2711 days ago850

reply all(2)I'll reply

  • PHPz

    PHPz2017-05-18 10:47:55

    a = "192.168.1.1-5,192.168.1.10-15"
    
    # 根据逗号分隔不同的ip, 结果是一个列表[192.168.1.1-5, 192.168.1.10-15]
    for ip in a.split(','):
        # ip就是遍历刚才的列表取得值, 根据.从右到左分割一次ip字符串, 获取结果192.168.1和1-5, 分别存给两个变量
        shuffix, _ = ip.rsplit('.', 1)
        # 用-切分1-5, 得出一个范围区间
        start, end = map(int, _.split('-'))
        for num in range(start, end+1):
            # num为上述范围区间的数, 然后拼接一开始的字符串, 组成新ip
            print('{}.{}'.format(shuffix, num))

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-18 10:47:55

    # coding: utf-8
    
    import os
    
    str = '192.168.1.1-5,192.168.1.10-15'
    
    for x in str.split(','):
        _, y = os.path.splitext(x)
        start, end = y.replace('.', '').split('-')
        for i in range(int(start), int(end) + 1):
            print '{}.{}'.format(_, i)

    reply
    0
  • Cancelreply