首页 > 解决方案 > 提取字符串中特定列下的值

问题描述

我的字符串如下

Module   Available     Used     Remaining
          (Watts)     (Watts)    (Watts) 
------   ---------   --------   ---------
1           485.0        0.0       485.0

我需要在Used. 我试图拆分字符串。有没有更好的方法来获得价值?

标签: pythonstringpython-3.x

解决方案


使用str.split

演示:

s = """Module   Available     Used     Remaining
          (Watts)     (Watts)    (Watts) 
------   ---------   --------   ---------
1           485.0        0.0       485.0"""

for i in s.split("\n"):
    if i.strip()[0].isdigit():
        val = i.split()
        print(val[2])

使用正则表达式:

import re
val = re.findall("\d+\s+\d*\s+\d*\.\d*\s+\d*\.\d*\s+\d*\.\d*", s)
for v in val:
    print(v.split()[2])

输出:

0.0

推荐阅读