1

My string is like below

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

I need to extract value under Used. I was trying to split the string. Is there any better way to get the value?

Georgy
  • 12,464
  • 7
  • 65
  • 73
Hiccup
  • 596
  • 6
  • 19
  • Maybe there is something helpful here: [Extract a column from a string in Python](https://stackoverflow.com/questions/27964942/extract-a-column-from-a-string-in-python) – Georgy May 06 '18 at 16:00

2 Answers2

2

Using str.split

demo:

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])

Using regex:

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])

Output:

0.0
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

Maybe this one is an overkill, but you can use to read a string in a dataframe and then get the desired value:

import io

import pandas as pd

your_string = io.StringIO("""Module   Available     Used     Remaining
          (Watts)     (Watts)    (Watts) 
------   ---------   --------   ---------
1           485.0        0.0       485.0""")

df = pd.read_csv(your_string, 
                 sep=" ", 
                 skipinitialspace=True, 
                 skiprows=[1, 2])

df will look like this:

    Module  Available   Used    Remaining
0   1   485.0   0.0     485.0

And

print(df.loc[0, 'Used'])

will give your 0.0.

P.S.: This was based on the following answer for the question "How to create a Pandas DataFrame from a string".

Georgy
  • 12,464
  • 7
  • 65
  • 73