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"
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
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'
Related
When I scrape a webpage it returns this: 42,834.56
Apparently, it extracts it as a word (because when I try to sum it whit the other ones retrieve in excel it doesn't work). How can I convert it into a number?
I'm copying from the cmd:
Here is an error when I write it with int():
Traceback (most recent call last):
File "C:\Users\Windows\Desktop\py4e\callao.py", line 337, in <module>
print(int(peso))
ValueError: invalid literal for int() with base 10: '42,834.56\xa0'
Here is an error when I write it with float():
Traceback (most recent call last):
File "C:\Users\Windows\Desktop\py4e\callao.py", line 337, in <module>
print(float(peso))
ValueError: could not convert string to float: '42,834.56\xa0'
You might need to remove ',' from the number. Try this:
float("".join(peso.split(',')))
a = "42,834.56"
b = float(a.replace(",",""))
print(type(b))
# output: <class 'float'>
You can try this.
Strip off the \xa0 character.
Remove the , from the string
Convert it to float.
s = '42,834.56\xa0'
s = s.strip()
print(float(s.replace(',','')))
You can store the scraped value in a variable and convert to float in python. Here's the function:
def convert_to_float(peso):
return float(peso.replace(',',''))
And here's the call to the function:
peso = '42,834.56'
convert_to_float(peso)
Output:
42834.56
Now you can sum it with others.
Edit -
It seems you have scraped \xa0 also along with the string. So to handle that:
def convert_to_float(peso):
peso = peso.split("\\")[0]
return float(peso.replace(',',''))
peso = '42,834.56\xa0'
convert_to_float(peso)
Output will be same as above.
Here is the code where I try to take the "t" char from the "two" string from the li list and compare it to a single "t" char:
li=["one","two","three"];
choice=1;
if li[choice[1]]=="t":
print("valid");
else:
print("unvalid");
The problem is that when I run it, it says:
Traceback (most recent call last):
File "C:\Users\Yobob\Documents\cours\ISN\ProjetISN\testPython.py", line 3, in <module>
if li[choice[1]]=="t":
TypeError: 'int' object is not subscriptable
choice[1] is doing 1[1] which doesn't make sense. I think you want li[choice][1]. i.e.
if li[choice][1] == "t":
I have Python (2.7) code which takes a float, formats it with thousand-separating commas and 3 decimal places, and adds the string literal " sec" afterwards.
The result is then formatted further by being aligned left and given a width of 20:
num = '{:,.3f} sec'.format(1200300.4443333333)
print '{:<20}'.format(num) + 'more'
Ouput:
1,200,300.444 sec more
I wanted to condense this into a single format call, but I couldn't figure out how to use the width properly with the string literal.
I tried the following:
num = '{:,.3f}'.format(1200300.4443333333)
print '{:<20} sec'.format(num) + 'more'
But the output isn't the same:
1,200,300.444 secmore
I also tried the following:
num = '{:,.3f}'.format(1200300.4443333333)
print '{:<20 sec}'.format(num) + 'more'
But that failed:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print '{:<20 sec}'.format(num) + 'more'
ValueError: Invalid conversion specification
Is there any way to condense the initial code into a single format call?
Not sure if it is but the following code might be what you're after:
num = '{:<20,.3f} sec more'.format(1200300.4443333333)
print(num)
# 1,200,300.444 sec more
This code prints out the tasklist of the OS. However, the following error is seen when it is run. Is there an easy solution to this problem?
"mem_usage":int(m.group(5).decode('ascii', 'ignore'))})
ValueError: invalid literal for int() with base 10: '11,440'
Code:
import re
from subprocess import Popen, PIPE, check_output
def get_processes_running():
"""
Takes tasklist output and parses the table into a dict
"""
tasks = check_output(['tasklist']).decode('cp866',
'ignore').split("\r\n")
p = []
for task in tasks:
m = re.match(b'(.*?)\\s+(\\d+)\\s+(\\w+)\\s+(\\w+)\\s+(.*?)\\s.*', task.encode())
if m is not None:
p.append({"image":m.group(1).decode(),
"pid":int(m.group(2).decode()),
"session_name":m.group(3).decode(),
"session_num":int(m.group(4).decode()),
"mem_usage":int(m.group(5).decode('ascii', 'ignore'))})
return p
def test():
print(*[line.decode('cp866', 'ignore') for line in Popen('tasklist', stdout=PIPE).stdout.readlines()])
lstp = get_processes_running()
for p in lstp:
print(p)
return
if __name__ == '__main__':
test()
I haven't fully read your code, but from your error, I would suggest using the .replace method on the string that you are trying to convert to an integer to remove all commas.
For instance, at the moment, you are doing something like:
>>> int('123,456')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '123,456'
which throws an error due to the comma marks. Simply remove all commas to fix this:
>>> int('123,456'.replace(',',''))
123456
See this:-
>>> int('23ds4')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23ds4'
This is the same case as yours. That character "," is also not an integer in that provided string. So it is not a valid argument.
You better replace those commas from your integer contained string:-
>>> s = '11,234,234'
>>> s.replace(',','')
'11234234'
My code for the sorting of the file.
g = open('Lapse File.txt', 'r')
column = []
i = 1
next(g)
for line in g:
column.append(int(line.split('\t')[2]))
column.sort()
This is the error I get.
Traceback (most recent call last):
File "E:/Owles/new lapse .py", line 51, in <module>
column.append(int(line.split('\t')[2]))
ValueError: invalid literal for int() with base 10: '-8.3\n
My main question is why is there a \n. Earlier in the code I had written to another text file and wrote it by column from a previously read in file.
This is my code for writing the file
for columns in (raw.strip().split() for raw in Sounding):
if (i >2 and i <=33):
G.write(columns [3]+'\t'+columns[2]+'\t'+columns[4]+'\n')
i = i + 1
elif (i >= 34):
G.write(columns [0]+'\t'+columns[1]+'\t'+columns[2]+'\n')
i = i + 1
else:
i = i + 1
I am unsure if writing the lines like that is the issue because I have inserted the new line function.
The traceback is telling you exactly what happened:
ValueError: invalid literal for int() with base 10: '-8.3\n'
The problem here is that, while int() can handle the negative sign and the trailing newline character, it can't handle the decimal point, '.'. As you know, -8.3 may be a real, rational number, but it's not an integer. If you want to preserve the fractional value to end up with -8.3, use float() instead of int(). If you want to discard the fractional value to end up with -8, use float() to parse the string and then use int() on the result.
-8.3:
column.append(float(line.split('\t')[2]))
-8:
column.append(int(float(line.split('\t')[2])))
Because only numeric strings can be cast to integers; look at this:
numeric_string = "109"
not_numeric_string = "f9"
This is okay:
>>> int(numeric_string)
109
And it cannot be cast:
>>> int(not_numeric_string)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'f9'
So somewhere in your script it is getting a non-numeric string.
It seems as though the "-8.3\n" string sequence has raised the error, so you must strip escape chars as well.