How to convert str to a float? - python

I imported a list full of floats as strings, and i tried to convert them to floats, but this error kept popping up
Traceback (most recent call last):
File "c:\Users\peter\Documents\coding\projects\LineFitting.py", line 12, in <module>
StockPriceFile = float(value.strip(''))
ValueError: could not convert string to float:
this is what i did to try and convert the list:
#1
for value in range(0, len(StockPriceFile)):
StockPriceFile[value] = float(StockPriceFile[value])
#2
for value in StockPriceFile:
value = float(value)
#3
StockPriceFile[0] = StockPriceFile[0].strip('[]')
for value in StockPriceFile:
StockPriceFile = float(value.strip(''))
(Sample Of Data)
['[36800.]', '36816.666666666664', '36816.666666666664', '36833.333333333336', '36866.666666666664']
where its being written:
Data_AvgFile.write(str(Average) + ',')
What does this mean? and how can i fix it? it works fine when i do it one by one.
(also tell me if you need more data, i dont know if this is sufficient)

for value in StockPriceFile:
stock_price = float(value.strip('[]'))
print(stock_price)
strip() will remove the [] characters around the value.
DEMO

As long you have the brackets "[ ]" in you'r string you cant convert it to a a number as that would make it invalid so do letters and most symbols the dot (.) is an exception for float.
>>> print(float('[36800.]'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '[36800.]'
>>> print(float('36800.'))
36800.0

l = ['[36800.]', '36816.666666666664', '36816.666666666664', '36833.333333333336', '36866.666666666664']
[float(f.strip('[]')) for f in l]
Output:
[36800.0,
36816.666666666664,
36816.666666666664,
36833.333333333336,
36866.666666666664]

Related

Function returns invalid literal for int() with base 10: ''

I have a function, that parses string and takes values by using indexes. When I try to take the exact variable and convert it into integer, it gives me a ValueError. The exact code part is:
y = special_string[y_start:y_end]
print(y)
y = int(y)
Traceback for it:
14
Traceback (most recent call last):
File "levelBuilder.py", line 255, in <module>
newLevel, rows, columns = importLevel(levelName)
File "levelBuilder.py", line 124, in importLevel
y = int(y)
ValueError: invalid literal for int() with base 10: ''
The question is - what can cause this error? As you see, y is integer (14). When I use the same method for another variable (x), it works correctly
14
Traceback (most recent call last): File "levelBuilder.py", line 255,
in
newLevel, rows, columns = importLevel(levelName)
It looks like there is a space line between the "exception message" and "14".
So, the y is ' ' , print(y) will print space line. int(y) will raise value err.
Maybe be you should remove the '*pyc' file and retry :-)

Placing variable in single quotes

I am receiving an integer error when reading from my CSV sheet. Its giving me problems reading the last column. I know theres characters in the last column but how do I define digit as a character. The API function psspy.two_winding_chg_4 requires an input using single quotes ' ' as shown below in that function(3rd element of the array)
Traceback (most recent call last):
File "C:\Users\RoszkowskiM\Desktop\win4.py", line 133, in <module>
psspy.two_winding_chng_4(from_,to,'%s'%digit,[_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i],[_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f, max_value, min_value,_f,_f,_f],[])
File ".\psspy.py", line 25578, in two_winding_chng_4
TypeError: an integer is required
ValueError: invalid literal for int() with base 10: 'T1'
The code:
for row in data:
data_location, year_link, from_, to, min_value,max_value,name2,tla_2,digit = row[5:14]
output = 'From Bus #: {}\tTo Bus #: {}\tVMAX: {} pu\tVMIN: {} pu\t'
if year_link == year and data_location == location and tla_2==location:
from_=int(from_)
to=int(to)
min_value=float(min_value)
max_value=float(max_value)
digit=int(digit)
print(output.format(from_, to, max_value, min_value))
_i=psspy.getdefaultint()
_f=psspy.getdefaultreal()
psspy.two_winding_chng_4(from_,to,'%s'%digit,[_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i,_i],[_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f,_f, max_value, min_value,_f,_f,_f],[])
The easiest and probable most usable option would be to used your own function to filter on only digits. Example:
def return_digits(string):
return int(''.join([x for x in string if x.isdigit()]))

python convert string like ['-0.88854965D+02'] to float

How to convert the string like '-0.88854965D+02' to float?
float('-0.88854965D+02') doesn't work:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): -0.88854965D+02
The string '-0.88854965D+02' appears to be written as scientific E notation. If that is the case, then you can use the following one-liner to replace the 'D' with 'E', and then convert to a float:
n = float('-0.88854965D+02'.replace("D", "E"))
print n
-88.854965

For loop error on a very simple program [Python]

Whenever I try to run the follwing code:
message = raw_input("Write a word: ")
for i in range (message(len)):
print i
I get this error:
Traceback (most recent call last):
File "C:\Python27\testing.py", line 3, in <module>
for i in range (message(len)):
TypeError: 'str' object is not callable
I have no idea why this is happening.
You need to apply len to the string, not the other way round.
This will work:
for i in range (len(message)):
print i
Note that this will print integers. You might actually want to do print message[i] to print each character in the string?
You're looking for range(len(message)), not range(message(len)). Your program will then print 0, 1, 2, etc. for each character in the string.

Type error in Python: need a single Unicode character as parameter

When I try to convert a unicode variable to float using unicodedata.numeric(variable_name), I get this error "need a single Unicode character as parameter". Does anyone know how to resolve this?
Thanks!
Here is the code snippet I'm using :
f = urllib.urlopen("http://compling.org/cgi-bin/DAL_sentence_xml.cgi?sentence=good")
s = f.read()
f.close()
doc = libxml2dom.parseString(s)
measure = doc.getElementsByTagName("measure")
valence = unicodedata.numeric(measure[0].getAttribute("valence"))
activation = unicodedata.numeric(measure[0].getAttribute("activation"))
This is the error I'm getting when I run the code above
Traceback (most recent call last):
File "sentiment.py", line 61, in <module>
valence = unicodedata.numeric(measure[0].getAttribute("valence"))
TypeError: need a single Unicode character as parameter
Summary: Use float() instead.
The numeric function takes a single character. It does not do general conversions:
>>> import unicodedata
>>> unicodedata.numeric('½')
0.5
>>> unicodedata.numeric('12')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: need a single Unicode character as parameter
If you want to convert a number to a float, use the float() function.
>>> float('12')
12.0
It won't do that Unicode magic, however:
>>> float('½')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '½'

Categories

Resources