user2133342
user2133342

Reputation: 161

python convert string "0" to float gives error

i have the following code in my python script, to launch an application and grab the output of it.

An example of this output would be 'confirmed : 0'

Now i only want to know the number, in this case zero, but normally this number is float, like 0.005464

When i run this code it tells me it cannot convert "0" to float. What am i doing wrong?

This is the error i get now: ValueError: could not convert string to float: "0"

cmd = subprocess.Popen('/Applications/Electrum.app/Contents/MacOS/Electrum getbalance', shell=True, stdout=subprocess.PIPE)
for line in cmd.stdout:
    if "confirmed" in line:
    a,b=line.split(': ',1)
    if float(b)>0:
        print "Positive amount"
    else:
        print "Empty"

Upvotes: 2

Views: 8405

Answers (2)

aifarfa
aifarfa

Reputation: 3939

I have tested the code and found that split(': ', 1) result contains string

>>> line = "1: 456: confirmed"
>>> "confirmed" in line
True
>>> a,b=line.split(': ', 1)
>>> a
'1'
>>> b
'456: confirmed'

Upvotes: -1

interjay
interjay

Reputation: 110118

According to the exception you got, the value contained in b is not 0, but "0" (including the quotes), and therefore cannot be converted to a float directly. You'll need to remove the quotes first, e.g. with float(b.strip('"')).

As can be seen in the following examples, the exception description does not add the quotes, so they must have been part of the original string:

>>> float('"0"')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: "0"
>>> float('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: a

Upvotes: 5

Related Questions