我有str格式的输出
Port Name Intvl In Mbps % In Kpps Out Mbps % Out Kpps
Et7/1 5:00 338.2 3.4% 31 0.0 12.3% 121
Run Code Online (Sandbox Code Playgroud)
我需要确定所有百分比,即3.4和12.3.做同样事情的最pythonic方法是什么
find_all with % just给出了索引,有没有更好的方法来实现呢?
\b\d+(?:\.\d+)?(?=%)
Run Code Online (Sandbox Code Playgroud)
与re.findall应该为你做.
print re.findall(r"\b\d+(?:\.\d+)?(?=%)",test_str)
Run Code Online (Sandbox Code Playgroud)
编辑:
如果你想要float价值而不是str使用
print map(ast.literal_eval,re.findall(r"\b\d+(?:\.\d+)?(?=%)",x))
Run Code Online (Sandbox Code Playgroud)
我们正在使用\b哪个是字边界.见演示