I’m running the following python script:
#!/usr/bin/python
import os,sys
from scipy import stats
import numpy as np
f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
w=f[i].split()
l1=w[1:8]
l2=w[8:15]
list1=[float(x) for x in l1]
list2=[float(x) for x in l2]
result=stats.ttest_ind(list1,list2)
print result[1]
However I got the errors like:
ValueError: could not convert string to float: id
I’m confused by this.
When I try this for only one line in interactive section, instead of for loop using script:
>>> from scipy import stats
>>> import numpy as np
>>> f=open('data2.txt','r').readlines()
>>> w=f[1].split()
>>> l1=w[1:8]
>>> l2=w[8:15]
>>> list1=[float(x) for x in l1]
>>> list1
[5.3209183842, 4.6422726719, 4.3788135547, 5.9299061614, 5.9331108706, 5.0287087832, 4.57...]
It works well.
Can anyone explain a little bit about this?
Thank you.
![]()
asked Dec 7, 2011 at 17:57
LookIntoEastLookIntoEast
7,58018 gold badges58 silver badges89 bronze badges
1
Obviously some of your lines don’t have valid float data, specifically some line have text id which can’t be converted to float.
When you try it in interactive prompt you are trying only first line, so best way is to print the line where you are getting this error and you will know the wrong line e.g.
#!/usr/bin/python
import os,sys
from scipy import stats
import numpy as np
f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
w=f[i].split()
l1=w[1:8]
l2=w[8:15]
try:
list1=[float(x) for x in l1]
list2=[float(x) for x in l2]
except ValueError,e:
print "error",e,"on line",i
result=stats.ttest_ind(list1,list2)
print result[1]
answered Dec 7, 2011 at 18:00
Anurag UniyalAnurag Uniyal
84.5k39 gold badges173 silver badges217 bronze badges
0
My error was very simple: the text file containing the data had some space (so not visible) character on the last line.
As an output of grep, I had 45 instead of just 45.
![]()
answered Nov 13, 2015 at 21:01
![]()
2
This error is pretty verbose:
ValueError: could not convert string to float: id
Somewhere in your text file, a line has the word id in it, which can’t really be converted to a number.
Your test code works because the word id isn’t present in line 2.
If you want to catch that line, try this code. I cleaned your code up a tad:
#!/usr/bin/python
import os, sys
from scipy import stats
import numpy as np
for index, line in enumerate(open('data2.txt', 'r').readlines()):
w = line.split(' ')
l1 = w[1:8]
l2 = w[8:15]
try:
list1 = map(float, l1)
list2 = map(float, l2)
except ValueError:
print 'Line {i} is corrupt!'.format(i = index)'
break
result = stats.ttest_ind(list1, list2)
print result[1]
answered Dec 7, 2011 at 17:59
For a Pandas dataframe with a column of numbers with commas, use this:
df["Numbers"] = [float(str(i).replace(",", "")) for i in df["Numbers"]]
So values like 4,200.42 would be converted to 4200.42 as a float.
Bonus 1: This is fast.
Bonus 2: More space efficient if saving that dataframe in something like Apache Parquet format.
answered Mar 12, 2021 at 11:49
![]()
ContangoContango
74.4k57 gold badges251 silver badges300 bronze badges
Perhaps your numbers aren’t actually numbers, but letters masquerading as numbers?
In my case, the font I was using meant that «l» and «1» looked very similar. I had a string like ‘l1919’ which I thought was ‘11919’ and that messed things up.
answered Mar 2, 2018 at 6:53
Tom RothTom Roth
1,85417 silver badges25 bronze badges
Your data may not be what you expect — it seems you’re expecting, but not getting, floats.
A simple solution to figuring out where this occurs would be to add a try/except to the for-loop:
for i in range(0,N):
w=f[i].split()
l1=w[1:8]
l2=w[8:15]
try:
list1=[float(x) for x in l1]
list2=[float(x) for x in l2]
except ValueError, e:
# report the error in some way that is helpful -- maybe print out i
result=stats.ttest_ind(list1,list2)
print result[1]
answered Dec 7, 2011 at 18:02
Matt FenwickMatt Fenwick
47.7k21 gold badges126 silver badges191 bronze badges
Shortest way:
df["id"] = df['id'].str.replace(',', '').astype(float) — if ‘,’ is the problem
df["id"] = df['id'].str.replace(' ', '').astype(float) — if blank space is the problem
answered Apr 26, 2021 at 13:46
Update empty string values with 0.0 values:
if you know the possible non-float values then update it.
df.loc[df['score'] == '', 'score'] = 0.0
df['score']=df['score'].astype(float)
answered Nov 24, 2021 at 7:42
![]()
I solved the similar situation with basic technique using pandas. First load the csv or text file using pandas.It’s pretty simple
data=pd.read_excel('link to the file')
Then set the index of data to the respected column that needs to be changed. For example, if your data has ID as one attribute or column, then set index to ID.
data = data.set_index("ID")
Then delete all the rows with «id» as the value instead of number using following command.
data = data.drop("id", axis=0).
Hope, this will help you.
answered Oct 3, 2019 at 14:44
![]()
I’m running the following python script:
#!/usr/bin/python
import os,sys
from scipy import stats
import numpy as np
f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
w=f[i].split()
l1=w[1:8]
l2=w[8:15]
list1=[float(x) for x in l1]
list2=[float(x) for x in l2]
result=stats.ttest_ind(list1,list2)
print result[1]
However I got the errors like:
ValueError: could not convert string to float: id
I’m confused by this.
When I try this for only one line in interactive section, instead of for loop using script:
>>> from scipy import stats
>>> import numpy as np
>>> f=open('data2.txt','r').readlines()
>>> w=f[1].split()
>>> l1=w[1:8]
>>> l2=w[8:15]
>>> list1=[float(x) for x in l1]
>>> list1
[5.3209183842, 4.6422726719, 4.3788135547, 5.9299061614, 5.9331108706, 5.0287087832, 4.57...]
It works well.
Can anyone explain a little bit about this?
Thank you.
![]()
asked Dec 7, 2011 at 17:57
LookIntoEastLookIntoEast
7,58018 gold badges58 silver badges89 bronze badges
1
Obviously some of your lines don’t have valid float data, specifically some line have text id which can’t be converted to float.
When you try it in interactive prompt you are trying only first line, so best way is to print the line where you are getting this error and you will know the wrong line e.g.
#!/usr/bin/python
import os,sys
from scipy import stats
import numpy as np
f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
w=f[i].split()
l1=w[1:8]
l2=w[8:15]
try:
list1=[float(x) for x in l1]
list2=[float(x) for x in l2]
except ValueError,e:
print "error",e,"on line",i
result=stats.ttest_ind(list1,list2)
print result[1]
answered Dec 7, 2011 at 18:00
Anurag UniyalAnurag Uniyal
84.5k39 gold badges173 silver badges217 bronze badges
0
My error was very simple: the text file containing the data had some space (so not visible) character on the last line.
As an output of grep, I had 45 instead of just 45.
![]()
answered Nov 13, 2015 at 21:01
![]()
2
This error is pretty verbose:
ValueError: could not convert string to float: id
Somewhere in your text file, a line has the word id in it, which can’t really be converted to a number.
Your test code works because the word id isn’t present in line 2.
If you want to catch that line, try this code. I cleaned your code up a tad:
#!/usr/bin/python
import os, sys
from scipy import stats
import numpy as np
for index, line in enumerate(open('data2.txt', 'r').readlines()):
w = line.split(' ')
l1 = w[1:8]
l2 = w[8:15]
try:
list1 = map(float, l1)
list2 = map(float, l2)
except ValueError:
print 'Line {i} is corrupt!'.format(i = index)'
break
result = stats.ttest_ind(list1, list2)
print result[1]
answered Dec 7, 2011 at 17:59
For a Pandas dataframe with a column of numbers with commas, use this:
df["Numbers"] = [float(str(i).replace(",", "")) for i in df["Numbers"]]
So values like 4,200.42 would be converted to 4200.42 as a float.
Bonus 1: This is fast.
Bonus 2: More space efficient if saving that dataframe in something like Apache Parquet format.
answered Mar 12, 2021 at 11:49
![]()
ContangoContango
74.4k57 gold badges251 silver badges300 bronze badges
Perhaps your numbers aren’t actually numbers, but letters masquerading as numbers?
In my case, the font I was using meant that «l» and «1» looked very similar. I had a string like ‘l1919’ which I thought was ‘11919’ and that messed things up.
answered Mar 2, 2018 at 6:53
Tom RothTom Roth
1,85417 silver badges25 bronze badges
Your data may not be what you expect — it seems you’re expecting, but not getting, floats.
A simple solution to figuring out where this occurs would be to add a try/except to the for-loop:
for i in range(0,N):
w=f[i].split()
l1=w[1:8]
l2=w[8:15]
try:
list1=[float(x) for x in l1]
list2=[float(x) for x in l2]
except ValueError, e:
# report the error in some way that is helpful -- maybe print out i
result=stats.ttest_ind(list1,list2)
print result[1]
answered Dec 7, 2011 at 18:02
Matt FenwickMatt Fenwick
47.7k21 gold badges126 silver badges191 bronze badges
Shortest way:
df["id"] = df['id'].str.replace(',', '').astype(float) — if ‘,’ is the problem
df["id"] = df['id'].str.replace(' ', '').astype(float) — if blank space is the problem
answered Apr 26, 2021 at 13:46
Update empty string values with 0.0 values:
if you know the possible non-float values then update it.
df.loc[df['score'] == '', 'score'] = 0.0
df['score']=df['score'].astype(float)
answered Nov 24, 2021 at 7:42
![]()
I solved the similar situation with basic technique using pandas. First load the csv or text file using pandas.It’s pretty simple
data=pd.read_excel('link to the file')
Then set the index of data to the respected column that needs to be changed. For example, if your data has ID as one attribute or column, then set index to ID.
data = data.set_index("ID")
Then delete all the rows with «id» as the value instead of number using following command.
data = data.drop("id", axis=0).
Hope, this will help you.
answered Oct 3, 2019 at 14:44
![]()
I’m running the following python script:
#!/usr/bin/python
import os,sys
from scipy import stats
import numpy as np
f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
w=f[i].split()
l1=w[1:8]
l2=w[8:15]
list1=[float(x) for x in l1]
list2=[float(x) for x in l2]
result=stats.ttest_ind(list1,list2)
print result[1]
However I got the errors like:
ValueError: could not convert string to float: id
I’m confused by this.
When I try this for only one line in interactive section, instead of for loop using script:
>>> from scipy import stats
>>> import numpy as np
>>> f=open('data2.txt','r').readlines()
>>> w=f[1].split()
>>> l1=w[1:8]
>>> l2=w[8:15]
>>> list1=[float(x) for x in l1]
>>> list1
[5.3209183842, 4.6422726719, 4.3788135547, 5.9299061614, 5.9331108706, 5.0287087832, 4.57...]
It works well.
Can anyone explain a little bit about this?
Thank you.
![]()
asked Dec 7, 2011 at 17:57
LookIntoEastLookIntoEast
7,58018 gold badges58 silver badges89 bronze badges
1
Obviously some of your lines don’t have valid float data, specifically some line have text id which can’t be converted to float.
When you try it in interactive prompt you are trying only first line, so best way is to print the line where you are getting this error and you will know the wrong line e.g.
#!/usr/bin/python
import os,sys
from scipy import stats
import numpy as np
f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
w=f[i].split()
l1=w[1:8]
l2=w[8:15]
try:
list1=[float(x) for x in l1]
list2=[float(x) for x in l2]
except ValueError,e:
print "error",e,"on line",i
result=stats.ttest_ind(list1,list2)
print result[1]
answered Dec 7, 2011 at 18:00
Anurag UniyalAnurag Uniyal
84.5k39 gold badges173 silver badges217 bronze badges
0
My error was very simple: the text file containing the data had some space (so not visible) character on the last line.
As an output of grep, I had 45 instead of just 45.
![]()
answered Nov 13, 2015 at 21:01
![]()
2
This error is pretty verbose:
ValueError: could not convert string to float: id
Somewhere in your text file, a line has the word id in it, which can’t really be converted to a number.
Your test code works because the word id isn’t present in line 2.
If you want to catch that line, try this code. I cleaned your code up a tad:
#!/usr/bin/python
import os, sys
from scipy import stats
import numpy as np
for index, line in enumerate(open('data2.txt', 'r').readlines()):
w = line.split(' ')
l1 = w[1:8]
l2 = w[8:15]
try:
list1 = map(float, l1)
list2 = map(float, l2)
except ValueError:
print 'Line {i} is corrupt!'.format(i = index)'
break
result = stats.ttest_ind(list1, list2)
print result[1]
answered Dec 7, 2011 at 17:59
For a Pandas dataframe with a column of numbers with commas, use this:
df["Numbers"] = [float(str(i).replace(",", "")) for i in df["Numbers"]]
So values like 4,200.42 would be converted to 4200.42 as a float.
Bonus 1: This is fast.
Bonus 2: More space efficient if saving that dataframe in something like Apache Parquet format.
answered Mar 12, 2021 at 11:49
![]()
ContangoContango
74.4k57 gold badges251 silver badges300 bronze badges
Perhaps your numbers aren’t actually numbers, but letters masquerading as numbers?
In my case, the font I was using meant that «l» and «1» looked very similar. I had a string like ‘l1919’ which I thought was ‘11919’ and that messed things up.
answered Mar 2, 2018 at 6:53
Tom RothTom Roth
1,85417 silver badges25 bronze badges
Your data may not be what you expect — it seems you’re expecting, but not getting, floats.
A simple solution to figuring out where this occurs would be to add a try/except to the for-loop:
for i in range(0,N):
w=f[i].split()
l1=w[1:8]
l2=w[8:15]
try:
list1=[float(x) for x in l1]
list2=[float(x) for x in l2]
except ValueError, e:
# report the error in some way that is helpful -- maybe print out i
result=stats.ttest_ind(list1,list2)
print result[1]
answered Dec 7, 2011 at 18:02
Matt FenwickMatt Fenwick
47.7k21 gold badges126 silver badges191 bronze badges
Shortest way:
df["id"] = df['id'].str.replace(',', '').astype(float) — if ‘,’ is the problem
df["id"] = df['id'].str.replace(' ', '').astype(float) — if blank space is the problem
answered Apr 26, 2021 at 13:46
Update empty string values with 0.0 values:
if you know the possible non-float values then update it.
df.loc[df['score'] == '', 'score'] = 0.0
df['score']=df['score'].astype(float)
answered Nov 24, 2021 at 7:42
![]()
I solved the similar situation with basic technique using pandas. First load the csv or text file using pandas.It’s pretty simple
data=pd.read_excel('link to the file')
Then set the index of data to the respected column that needs to be changed. For example, if your data has ID as one attribute or column, then set index to ID.
data = data.set_index("ID")
Then delete all the rows with «id» as the value instead of number using following command.
data = data.drop("id", axis=0).
Hope, this will help you.
answered Oct 3, 2019 at 14:44
![]()
The Python error “ValueError: could not convert string to float” occurs when you try to call float() on a string that can’t be converted to a floating point number. This can be because it has a comma or other non-number character in it. Fix it by removing the invalid characters, using a try / except block, or with regular expressions.
Python has a lot of really helpful built-in features. That’s what makes it so much more programmer-friendly than old-school languages like C. But, for as good as these built-ins are, they can’t do everything. Converting strings to numbers is a common problem, and usually Python handles this pretty well. One place it’s lacking, though, is handling non-numeric characters like dollar signs or commas, which are common in numbers that appear as strings.
Let’s say you’re working on a web scraping app. That app pulls raw HTML off of a webpage, does some parsing with something like Beautiful Soup, then pulls numbers out of the readable text, like, say, prices of things on Amazon. You’d think you could convert that to a float with the float() built-in function, but you’d be mistaken.
Let’s look at some examples of problems you might have that result in a ValueError from converting strings to floating point numbers.
❌ Problem: You have commas or other invalid characters in your string
Keeping with the example we mentioned in our intro, let’s say you have a price represented as a string and you want to convert that to a floating point number. This is a common occurrence. If you pulled that number straight from the web, it probably looks something like this: $19.95. You and I know what that value is as a floating point, but Python sure doesn’t.
Here’s an example of some code that will absolutely not work:
price = "$19.95" price_as_float = float(price) print(price_as_float)
Seems easy enough. All we have is a price that we want to call float() on to convert the string to a floating point number, presumably so we can do math on it, sort it, compare it, etc. You know, the normal stuff one does with prices.
But here’s what happens when we try to do this:
Traceback (most recent call last):
File "/home/user/main.py", line 2, in <module>
price_as_float = float(price)
ValueError: could not convert string to float: '$19.95'
Hmm… that didn’t work, did it. What options do we have? Well, there’s a couple. Let’s start with the simplest option, one that doesn’t require installing any other Python packages.
✅ Fix 1: remove currency signs and other invalid leading or trailing characters with .strip()
Python is really good at string manipulation. It has so many cool built-in features that make it a breeze. For our purposes, we can look at the .strip() method that is built in to all strings. What .strip() does is it removes the characters you provide it from the beginning or ending of the string you call it on.
If we know we just need to remove a dollar sign ($) from the beginning of a string, all we need to do is pass that to .strip() before trying to call float() on it:
price = "$19.95"
price_as_float = float(price.strip("$"))
print(price_as_float)
# -> 19.95
Nice! This gives us the result we want. But what if there’s commas and other stuff? This method won’t work… let’s look at a more complete solution for this.
✅ Fix 2: remove all invalid characters with .replace()
If your string has a bunch of weird stuff in it, or if it just has a comma (,), then it’s going to throw a wrench into our .strip() method above since it only removes characters from the beginning or end of the string. If we want to remove characters from the middle, we need .replace().
Let’s say our price is $1,999.95 this time. If we use .strip() it won’t work because there’s a comma. Here’s how we can use .replace() a couple times instead to achieve a good conversion:
price = "$1,999.95"
price_as_float = float(price.replace("$", "").replace(",", ""))
print(price_as_float)
# -> 1999.95
So, this worked, but it’s really ugly. What we did was we first replaced the “$” with an empty string, effectively stripping it out of the string altogether. Then, we did the same thing with the “,”.
Question: why did we have to use .replace() twice?
We had to use .replace() twice because it only replaces a substring, not individual characters. So if we want to remove multiple single characters, we have to call it as many times as we have characters we want to remove. For example, price.replace("$,", "") will not work. It will look for the substring "$,", which doesn’t exist in our price, and will just return the original string to us. We don’t want that.
A less janky solution is to use regular expressions. But, fair warning, they’re not for the feint of heart.
✅ Fix 3: remove invalid characters with a regular expression
This is my recommended solution which will handle a lot of other edge cases pretty elegantly. Instead of calling .strip() to only take care of stuff at the beginning or end of a string, and instead of calling .replace() a bunch of times, we can take care of it all in one go using the built-in re package.
Let’s look at the solution first then I’ll explain it:
import re price = "$1,999.95" price_as_float = float(re.sub(r"[^d.]", "", price)) print(price_as_float) # -> 1999.95
That’s all there is to it. Now, what we did here was we used a regular expression to strip out everything that isn’t a digit (d) or a decimal point (.) by replacing it with an empty string using the re.sub() function. All that function does is substitute a regular expression pattern with whatever the second parameter is. In our case, it was nothing, because we want to get rid of those characters.
This also neatly sidesteps locality issues, such as having £ or €, or any other currency sign / random characters in the price. It also works if you have the price chilling out in a full sentence like this:
import re price = "The price is $1,999.95" price_as_float = float(re.sub(r"[^d.]", "", price)) print(price_as_float) # -> 1999.95
Pretty cool!
❌ Problem: Your string is not a number at all
Sometimes you’re trying to parse something that just isn’t a number. This can happen if your code is being called by someone else, or something else, like another application or service. Here’s an example of our re method on something that won’t work:
import re price = "This isn't a price at all! Haha!" price_as_float = float(re.sub(r"[^d.]", "", price)) print(price_as_float)
When we try to run this, we’ll get the following error:
Traceback (most recent call last):
File "/home/user/main.py", line 4, in <module>
price_as_float = float(re.sub(r"[^d.]", "", price))
ValueError: could not convert string to float: ''
Looks like there wasn’t any price in there 🙁
What happened here? Well, our regular expression did what it was supposed to do, it stripped out everything that wasn’t a digit or a decimal point. What we were left with was an empty string, which, of course, can’t be converted to a floating point number. So how do we handle this?
Trick question, we don’t! Or rather, we handle not handling it. Make sense? No? Good.
✅ Fix: use a try / except block to test the string first
All joking aside, in this case and in almost every other situation, it’s best to use a try / except block if we’re not sure the thing we’re about to do will succeed. For our example, we’ll pair the re method with a try / except block:
import re
try:
price = "This isn't a price at all! Haha!"
price_as_float = float(re.sub(r"[^d.]", "", price))
print(price_as_float)
except ValueError:
print("Couldn't convert to float :(")
# -> Couldn't convert to float :(
This way, you tried your best, and if that wasn’t good enough, at least we can handle the error gracefully instead of crashing our whole application with a stack trace 😉
Conclusion
In this post we covered the various causes of “ValueError: could not convert string to float” as well as a few different ways to handle it. In short, it’s always caused by trying to parse a string that contains anything other than digits and one decimal point. If you know you just need to strip a currency sign, go ahead and use .strip() on the string first. If you have other stuff within the number, or if the number is part of a much longer string like a full sentence, use re to strip everything else out.
And, as always, if you’re not sure the thing will convert at all, use try / except to handle that error gracefully.
That’s all for now, happy coding!
The ValueError: could not convert string to float error occurs when you try to convert a string that does not contain a float number to a float. If the python string is not formatted as a floating point number, you could not convert string to float. The python ValueError: could not convert string to float will be thrown. The error is caused by a parsing error in the float() function with a string argument that cannot be parsed as a float number.
The float() function is used to convert a string with a float value to a float value. The float function parses the string and converts it as a float number. If an error occurs while converting a string to a float number, the python interpreter will throws this value error.
The string is supposed to have a valid float number. If the string is empty or does not contain a valid float number, the python interpreter can not convert it to a float number while parsing the string. In this case, the error “ValueError: could not convert string to float:” is thrown by the python interpreter.
Exception
The error “ValueError: could not convert string to float:” will be shown as below the stack trace.
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 1, in <module>
print float('')
ValueError: could not convert string to float:
[Finished in 0.0s with exit code 1]
Root Cause
The function float() is used to convert a string to a float number. The string is supposed to have a valid float number. If the string is either empty or does not have a valid float number, the python interpreter will throw an error while parsing the string. If the valid float value is passed to the string, this issue will be resolved.
Valid arguments in float() function
The following are the valid arguments for float() function. If you use one of the following, the error will not be thrown.
float() function with no argument – The default float() function which has no argument passed returns default value 0.0.
print float() # returns 0.0
float() function with an integer value – If an integer value is passed as an argument in float() function, returns the float value.
print float(5) # returns 5.0
float() functions with a string containing an integer value – If a string having an integer value is passed as an argument in float() function, returns the float value.
print float('5') # returns 5.0
float() function with a float value – If a float value is passed as an argument in float() function, returns the float value.
print int(5.4) # returns 5.4
float() functions with a string containing an float value – If a string having an float value is passed as an argument in float() function, returns the float value.
print float('5.4') # returns 5.4
float() function with a boolean value – If a boolean value is passed as an argument in float() function, returns the float value for the boolean value.
print float(True) # returns 1.0
Invalid arguments in float() function
float() function with an empty string – The empty string can not be parsed as an float value
print float('') # throws ValueError: could not convert string to float:
float() function with a non-float string – If a string contains a non-float values such as characters and passed as an argument, the float() function will throw value error.
print float('q') # throws ValueError: could not convert string to float: q
Solution 1
The string value should be checked whether it is a number or not using buid-in isnumeric() function. If a string contains a number, it is passed as an argument in the float() function. Otherwise, the user will be shown an error message.
Program
x='a'
print float(x)
Output
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 2, in <module>
print float(x)
ValueError: could not convert string to float: a
[Finished in 0.0s with exit code 1]
Solution
x= u'a'
if x.isnumeric():
print "float value is " , float(x)
else :
print "Not a number"
Output
Not a number
[Finished in 0.1s]
Solution 2
If a string occasionally contains a non-numeric number, the build-in function isnumeric() is not a good option. In this case, try catch method will solve this issue. If the string contains an float number, it will be executed in the try block. Otherwise, an error message will be shown to the user in the error block.
Program
x='a'
print float(x)
Output
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 2, in <module>
print float(x)
ValueError: could not convert string to float: a
[Finished in 0.0s with exit code 1]
Solution
x= u'a'
try:
print ("float value is " , float(x))
except:
print "Not a number"
Output
Not a number
[Finished in 0.1s]
Table of Contents
Hide
- ValueError: could not convert string to float
- Exception could not convert string to float
- Fix ValueError: could not convert string to float
- Solution 1: Ensure the string has a valid floating value
- Solution 2: Use try-except
If you convert a string object into a floating-point in Python many times you will get a ValueError: could not convert string to float. Usually, this happens if the string object has an invalid floating value with spaces or comma Python will throw ValueError while parsing into string object into float.
In this article, we will take a look at what this error means and how to fix this error in your code with examples.
If we are reading and processing the data from excel or CSV, we get the numbers in the form of a string, and in the code, we need to convert from string to float.
Python has a built-in float() method that can parse the string to a floating-point number. This method will be useful when we need to perform a mathematical operation on a string object.
The float() method only allows you to convert strings that hold float-like numbers. This means that you cannot convert a value if
- A value contains spaces
- A value contains a comma
- A value contains special characters
Exception could not convert string to float
order_value = '12,000'
tax_percentage = 4
tax_amount = (float(order_value)*(tax_percentage / 100))
print("The total tax amount is ", tax_amount)
Output
Traceback (most recent call last):
File "c:/Projects/Tryouts/main.py", line 4, in <module>
tax_amount = (float(order_value)*(tax_percentage / 100))
ValueError: could not convert string to float: '12,000'
Let’s take a simple example to demonstrate the ValueError exception. In the below code, we have the total order value in terms of USD, and we are accepting this in string format and performing a tax calculation.
If you see the above code, the order value has a comma-separated numeric value, and while parsing into a float, Python will throw ValueError: could not convert string to float.
There are a few other scenarios where you could get ValueError.
- Converting an empty string into a floating-point number
- Converting a non-floating string to a floating-point number
Fix ValueError: could not convert string to float
There are multiple ways to resolve the issue. Let’s take a look at each of the solutions.
Solution 1: Ensure the string has a valid floating value
The easiest way is to clean up the data or pass it in the correct format if we already know the data format before converting it into float.
If the value has a comma, space, or any special characters, then it needs to be processed before converting into float.
In the below code, we are storing a valid float number as a string, and later we are converting that into floating-point to calculate tax.
Example:
order_value = '12000'
tax_percentage = 4
tax_amount = (float(order_value)*(tax_percentage / 100))
print("The total tax amount is ", tax_amount)
Output
The total tax amount is 480.0
Solution 2: Use try-except
The best way is to handle the exception in case of an invalid data format. In the below code, it will run the code in the try block. If the conversion fails, then it runs the except block code.
Example:
order_value = '12,000'
tax_percentage = 4
try:
tax_amount = (float(order_value)*(tax_percentage / 100))
print("The total tax amount is ", tax_amount)
except:
print ("Order value is invalid")
Output
Order value is invalid

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.