Reputation: 53
This one is hopefully simple, I have a string "voltage is E=200V and the current is I=4.5A". I need to extract both float values. I have tried to use the float() function (with a sub-string of 11 to 16 in the parameters) but i get an error. I realize this probably is not good coding, I am in the beginning stages of trying to learn Python. Any help is much appreciated.
edit: Here is the code
I = 0.0
if((currentString.find('I=')) != -1):
I = float(currentString[(currentString.find('I=')):(currentString.find('A'))])
again, im new to this language and i know that looks ugly.
Upvotes: 1
Views: 2385
Reputation: 3417
I'm reluctant to mention regular expressions, as it is often a confusing tool for novices, but for your use and reference, here is a snippet that should help you get those values. IIRC voltage is unlikely to be float(instead int?), so this matching operating returns int later, but can be float if that is really required.
>>> import re
>>> regex = re.compile(r'.*?E=([\d.]+).*?I=([\d.]+)')
>>> re.match('voltage is E=200V and the current is I=4.5A')
>>> matches = regex.match('voltage is E=200V and the current is I=4.5A')
>>> int(matches.group(1))
200
>>> float(matches.group(2))
4.5
A method to extract such numbers using more simple tools is:
>>> s.find('E=')
11
>>> s.find('V', 11)
16
>>> s[11:16]
'E=200'
>>> s[11+2:16]
'200'
>>> int(s[11+2:16])
200
Upvotes: 2