Python 正在提取字符串中的%个匹配项
我有以下str格式的输出Python 正在提取字符串中的%个匹配项,python,regex,Python,Regex,我有以下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。 做同样的事,最具蟒蛇风格的方式是什么 用%查找所有内容只是给出了索引,有没有
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。
做同样的事,最具蟒蛇风格的方式是什么
用%查找所有内容只是给出了索引,有没有更好的方法来实现这一点
\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
,它用于单词边界
用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
表示单词边界。它给出['4',3']而不是[3.4,12.3]它给出['4',3']而不是[3.4,12.3]