jgr208
jgr208

Reputation: 3066

Get a value from a string in python

Program Details:

I am writing a program for python that will need to look through a text file for the line:

Found mode 1 of 12: EV= 1.5185449E+04, f= 19.612545, T= 0.050988.

Problem:

Then after the program has found that line, it will then store the line into an array and get the value 19.612545, from f = 19.612545.

Question:

I so far have been able to store the line into an array after I have found it. However I am having trouble as to what to use after I have stored the string to search through the string, and then extract the information from variable f. Does anyone have any suggestions or tips on how to possibly accomplish this?

Upvotes: 0

Views: 17723

Answers (2)

Florin Stingaciu
Florin Stingaciu

Reputation: 8275

Using regular expressions here is maddness. Just use string.find as follows: (where string is the name of the variable the holds your string)

index = string.find('f=')
index = index + 2 //skip over = and space 
string = string[index:] //cuts things that you don't need 
string = string.split(',') //splits the remaining string delimited by comma
your_value = string[0] //extracts the first field

I know its ugly, but its nothing compared with RE.

Upvotes: 0

AlG
AlG

Reputation: 15157

Depending upon how you want to go at it, CosmicComputer is right to refer you to Regular Expressions. If your syntax is this simple, you could always do something like:

line = 'Found mode 1 of 12: EV= 1.5185449E+04, f= 19.612545, T= 0.050988.'

splitByComma=line.split(',')

fValue = splitByComma[1].replace('f= ', '').strip()
print(fValue)

Results in 19.612545 being printed (still a string though).

Split your line by commas, grab the 2nd chunk, and break out the f value. Error checking and conversions left up to you!

Upvotes: 7

Related Questions