使用regex
:
>>> s = '1.2.3.4.5.6.7'
>>> re.search(r'(\d+\.\d+)', s).group()
'1.2'
时间比较:
>>> r = re.compile(r'^(\d+\.\d+)')
>>> s = '100.21.3.4.5.6.7'
>>> %timeit r.search(s).group()
100000 loops, best of 3: 1.43 us per loop
>>> %timeit '.'.join(s.split('.')[:2])
1000000 loops, best of 3: 2.32 us per loop
>>> %timeit '.'.join(s.split('.', 2)[:-1])
100000 loops, best of 3: 1.28 us per loop
>>> s = '100.21.3.4.5.6.7'*100
>>> %timeit r.search(s).group()
1000000 loops, best of 3: 1.96 us per loop
>>> %timeit '.'.join(s.split('.')[:2])
10000 loops, best of 3: 40.4 us per loop
>>> %timeit '.'.join(s.split('.', 2)[:-1])
100000 loops, best of 3: 2.01 us per loop
>>> s = '100.21.3.4.5.6.7'*1000
>>> %timeit r.search(s).group()
1000000 loops, best of 3: 1.94 us per loop
>>> %timeit '.'.join(s.split('.')[:2])
1000 loops, best of 3: 314 us per loop
>>> %timeit '.'.join(s.split('.', 2)[:-1])
100000 loops, best of 3: 6.76 us per loop
>>> s = '100.21.3.4.5.6.7'*10000
>>> %timeit r.search(s).group()
100000 loops, best of 3: 1.42 us per loop
>>> %timeit '.'.join(s.split('.')[:2])
100 loops, best of 3: 5.3 ms per loop #millisecond
>>> %timeit '.'.join(s.split('.', 2)[:-1])
10000 loops, best of 3: 104 us per loop
re.findall
基于解决方案的速度也会很慢,因为它需要对整个字符串进行迭代,而re.search
在第一次匹配时停止。