1

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.

  • Can you show us your code? s = '200'; float(s) should work. – George Apr 7 '12 at 22:41
  • the substring is E=200V, which is not a valid float. You need to be a lot more specific, you need to include code, and you need to include the error you get with a traceback. – Niklas B. Apr 7 '12 at 22:42
  • I am not sure if this works for you: ideone.com/ynjW3 . Tell us more specific on your error if you encounter any. – George Apr 7 '12 at 22:45
  • @George and Niklas, Basically I have to search the string and return the float values found. Im not really sure how to go about doing this which is why i require assistance. The error is:ValueError: could not convert string to float: 'I=4.5A'. I understand why this cannot be done, I just cant think of how to extract the float values. Thanks guys – MellowFellow Apr 7 '12 at 22:54
  • float I = 0.0 will generate a syntax error. – Joel Cornett Apr 8 '12 at 1:19
2

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
| improve this answer | |
  • Thank you! I'm kind of mad I couldn't think of this :/, but thanks a lot man – MellowFellow Apr 7 '12 at 23:04
  • You may want to add '-' in between the [] if voltages or amps can be negative. I'm no electrical engineer. ;) – Kurt Apr 8 '12 at 5:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.