Pythonic分裂字符串的方法然后再次分裂结果?

时间:2016-09-29 15:55:10

标签: python split idiomatic

有更多的pythonic方法吗

def parse_address(hostname, addresses):
    netmask=''
    for address in addresses:
        if hostname in address:
            _hostname, _netmask = address.strip().split('/')
            hostname = _hostname.split()[-1]
            netmask = '/' + _netmask.split()[0]
            break

    return netmask

测试用例

如果你做TDD

def test_parse_netmask(self):
        hostname = '127.0.0.1'

        stdout = [
            "1: lo    inet 127.0.0.1/8 scope host lo\       valid_lft forever preferred_lft forever",
            "3: wlp4s0    inet 192.168.2.133/24 brd 192.168.2.255 scope global dynamic wlp4s0\       valid_lft 58984sec preferred_lft 58984sec",
            "4: docker0    inet 172.17.0.1/16 scope global docker0\       valid_lft forever preferred_lft forever",
            "5: br-a49026d1a341    inet 172.18.0.1/16 scope global br-a49026d1a341\       valid_lft forever preferred_lft forever",
            "6: br-d26f2005f732    inet 172.19.0.1/16 scope global br-d26f2005f732\       valid_lft forever preferred_lft forever",
        ]

        netmask = scanner.parse_address(hostname, stdout)

        self.assertEqual(netmask, '/8')

3 个答案:

答案 0 :(得分:1)

def x(hostname,addresses):
    import re 
    for address in addresses:
        result = re.search(hostname+r"/\d", address)
        if result:
            return result.group(0).split(hostname)[1]

不知道它是否更像'Pythonic',但我会这样做。它对其他人来说是可读的,但它足够短,不能拖延功能。

答案 1 :(得分:0)

import re
hostname = '127.0.0.1'
stdout = [
            "1: lo    inet 127.0.0.1/8 scope host lo\       valid_lft forever preferred_lft forever",
            "3: wlp4s0    inet 192.168.2.133/24 brd 192.168.2.255 scope global dynamic wlp4s0\       valid_lft 58984sec preferred_lft 58984sec",
            "4: docker0    inet 172.17.0.1/16 scope global docker0\       valid_lft forever preferred_lft forever",
            "5: br-a49026d1a341    inet 172.18.0.1/16 scope global br-a49026d1a341\       valid_lft forever preferred_lft forever",
            "6: br-d26f2005f732    inet 172.19.0.1/16 scope global br-d26f2005f732\       valid_lft forever preferred_lft forever",
        ]

print [item.split('/')[-1] for item in re.findall(r'(?:\d+\.){3}\d+\/\d+',''.join(stdout)) if hostname  in item]

['8']

答案 2 :(得分:-1)

你能将它建立在像这样的代码上吗?

from urllib.parse import urlparse

parseResult = urlparse('http://www.fake.ca/185')
print ( parseResult )

parseResult是一个结构,其元素在print语句的输出中显示。

ParseResult(scheme ='http',netloc ='www.fake.ca',path ='/ 185',params ='',query ='',fragment ='')