Skip to main content
 首页 » 编程设计

python之提取字符串中出现的百分比

2025年05月04日41telwanggs

我有以下 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 

我需要精确计算所有出现的百分比,即 3.4 和 12.3。 做同样的事情最pythonic的方法是什么

find_all with % 只是给出索引,有没有更好的方法来实现这个?

请您参考如下方法:

\b\d+(?:\.\d+)?(?=%) 

re.findall 应该会为您完成。

print re.findall(r"\b\d+(?:\.\d+)?(?=%)",test_str) 

编辑:

如果你想要 float 值而不是 str 使用

print map(ast.literal_eval,re.findall(r"\b\d+(?:\.\d+)?(?=%)",x)) 

我们正在使用 \b 用于单词边界。 See Demo