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]
Answer from Anurag Uniyal on Stack Overflow
🌐
Python.org
discuss.python.org › python help
Could not convert string to float - Python Help - Discussions on Python.org
January 6, 2022 - Hi! I have a “txt” file, which has several numbers like this: 1 2 3 4 I want my programme to sum all of them. I’ve done the following: file=open(“n38.txt”, “r”) result=0 for line in file: n=float(line) print(n) result=result+n print(“the sum is”, result) But I get the mistake: ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › cannot-convert-string-to-float-in-python
Cannot Convert String To Float in Python - GeeksforGeeks
July 23, 2025 - The "Cannot Convert String to Float" error in Python typically occurs when attempting to convert a string to a float data type, but the string content is not a valid numeric representation.
Discussions

python - ValueError: could not convert string to float: id - Stack Overflow
Obviously some of your lines don't ... 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 ... More on stackoverflow.com
🌐 stackoverflow.com
Value error in Python: Could not convert string to float: Male
Hi All, I hope this message finds you well. I have encountered an error and hoping is someone could assist me in getting this resolved. I attempted to make a countplot with the Gender attribute however, when executing the code, I have received, ValueError: could not convert string to float: ... More on discuss.python.org
🌐 discuss.python.org
0
0
January 24, 2024
Confusing python - Cannot convert string to float
I got a value error and even if I try playing around with the code, it doesn't work! How can I get it right? - I am using Python 3.3.2! Here is the code: As you can see, the program asks for ho... More on stackoverflow.com
🌐 stackoverflow.com
ValueError: could not convert string to float
Your string not only includes double-quotes, but also a newline character. You need to remove those before you can convert it to a float, i.e. the string needs to look like '104.8' or the equivalent "104.8", but not like '"104.8\n"' or the equivalent "\"104.8\"\n". More on reddit.com
🌐 r/learnpython
11
1
April 22, 2022
🌐
Python.org
discuss.python.org › python help
Could not convert string to float: '' - Python Help - Discussions on Python.org
June 6, 2024 - Hi to everybody, In pandas I want to convert a string column in a float one, but I get all the time the same error message: could not convert string to float: ‘’ The content of this column is the following: 2019-08-06T16:47:07.508 So I replaced “-”, “T”, “:” and “.” with following code: climbing[“UTC time”] = climbing[“UTC time”].replace(“-”, “”, regex=True) climbing[“UTC time”] = climbing[“UTC time”].replace(“:”, “”, regex=True) climbing[“UTC time”] = climbing[“UTC time”].replace(“.”, “”,...
🌐
Codedamn
codedamn.com › news › programming
Fix ValueError: could not convert string to float
November 7, 2022 - This error is encountered if we intend to convert a string that cannot be converted to the float() data type. This kind of conversion is not supported till the latest version of Python i.e. 3.10.7. . We face this issue in various places: ... ...
🌐
Python.org
discuss.python.org › python help
Value error in Python: Could not convert string to float: Male - Python Help - Discussions on Python.org
January 24, 2024 - Hi All, I hope this message finds you well. I have encountered an error and hoping is someone could assist me in getting this resolved. I attempted to make a countplot with the Gender attribute however, when executing the code, I have received, ValueError: could not convert string to float: ...
🌐
Career Karma
careerkarma.com › blog › python › python valueerror: could not convert string to float solution
Python valueerror: could not convert string to float Solution | CK
December 1, 2023 - You can solve this error by adding a handler that makes sure your code does not continue running if the user inserts an invalid value. Alternatively, you can add in additional input validation before converting a number to a float() to make ...
Find elsewhere
Top answer
1 of 4
10

You need to take into account that the user might not fill in a proper value:

try:
    miles = float(input("How many miles can you walk? "))
except ValueError:
    print("That is not a valid number of miles")

A try/except handles the ValueError that might occur when float tries to convert the input to a float.

2 of 4
4

The problem is exactly what the Traceback log says: Could not convert string to float

  • If you have a string with only numbers, python's smart enough to do what you're trying and converts the string to a float.
  • If you have a string with non-numerical characters, the conversion will fail and give you the error that you were having.

The way most people would approach this problem is with a try/except (see here), or using the isdigit() function (see here).

Try/Except

try:
    miles = float(input("How many miles can you walk?: "))
except:
    print("Please type in a number!")

Isdigit()

miles = input("How many miles can you walk?: ")
if not miles.isdigit():
    print("Please type a number!")

Note that the latter will still return false if there are decimal points in the string

EDIT

Okay, I won't be able to get back to you for a while, so I'll post the answer just in case.

while True:
    try:
        miles = float(input("How many miles can you walk?: "))
        break
    except:
        print("Please type in a number!")

#All of the ifs and stuff

The code's really simple:

  • It will keep trying to convert the input to a float, looping back to the beginning if it fails.
  • When eventually it succeeds, it'll break from the loop and go to the code you put lower down.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-valueerror-could-not-convert-string-to-float
ValueError: could not convert string to float in Python | bobbyhadz
To solve the "ValueError: could not convert string to float" error, make sure: The string doesn't contain spaces or non-digit characters. The string contains a period . as the decimal separator and not a comma ,. The string is not empty.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-convert-string-to-float
How to Convert String to Float in Python: Complete Guide with Examples | DigitalOcean
July 10, 2025 - This is the standard Pythonic way to handle exceptions in Python. ... The try block contains the code that might fail (the “risky” operation). The except block contains the code that runs only if an error occurs in the try block. This allows you to catch the ValueError and handle it gracefully instead of letting your program terminate. input_string = "not a number" value_float = 0.0 try: value_float = float(input_string) print("Conversion successful!") except ValueError: print(f"Could not convert '{input_string}'.") print(f"The final float value is: {value_float}")
🌐
Statology
statology.org › home › how to fix in pandas: could not convert string to float
How to Fix in Pandas: could not convert string to float
July 16, 2022 - #attempt to convert 'revenue' from string to float df['revenue'] = df['revenue'].astype(float) ValueError: could not convert string to float: '$400.42'
🌐
Python Guides
pythonguides.com › could-not-convert-string-to-float-python
Could Not Convert String To Float In Python
April 18, 2024 - In the solution, we use the replace() method to replace the “$” sign with the empty string, so now only the numeric part is left. If the string contains only the numeric part, it can be converted to a float in Python using the float() method.
🌐
AskPython
askpython.com › home › resolving python’s valueerror: cannot convert string to float
Resolving Python's ValueError: Cannot Convert String to Float - AskPython
May 25, 2023 - And, if we give a proper float ... Except · We can also use the if and not statements with each other along with the isdigit() function....
🌐
Reddit
reddit.com › r/learnpython › python pandas - can't convert string to float (i think b/c of multiple data types in column...)
r/learnpython on Reddit: Python pandas - can't convert string to float (I think b/c of multiple data types in column...)
July 17, 2022 -

I want to do some math on a dataframe but (I think) can't get one column/series into the necessary format. The column contains strings; some are '.123' while others are '0'. When I attempt the math on the column of strings by converting everything to an integer like so:

dfteam1['cloff'] = dfteam1.cloff.astype(int)

I get the following error

ValueError: invalid literal for int() with base 10: '.123'

I think it's b/c .123 isn't an integer but a float, so I change the code like so:

dfteam1['cloff'] = dfteam1.cloff.astype(float)

now I get the following error

ValueError: could not convert string to float:

I think it's b/c 0 isn't a float but an integer? Do I need to change all the 0 values to 0.00 or am I completely off base? All feedback is welcome.

🌐
PyiHub
pyihub.org › home › valueerror could not convert string to float solved
ValueError Could Not Convert String to Float Solved
April 3, 2024 - ValueError could not convert string to float when we tried to convert a string into float. In Python, a string can be converted into a float value only if the string has numeric values
🌐
Medium
kasata.medium.com › debugging-the-valueerror-could-not-convert-string-to-float-python-error-a48944439ab5
Debugging the “ValueError: could not convert string to float:” Python Error | by KASATA - TechVoyager | Medium
April 24, 2024 - If the string has any character that can’t be converted to a float, you should handle it before performing the conversion. There are several ways you can handle this error: Using Exception Handling: This method involves using try and except blocks to catch and handle the error. Code: try: my_string = “123.456A” print(float(my_string)) except ValueError: print(“Conversion failed”) Output: Conversion failed
🌐
Reddit
reddit.com › r/learnpython › exception has occurred: valueerror could not convert string to float: '\n' python code
r/learnpython on Reddit: Exception has occurred: ValueError could not convert string to float: '\n' python code
September 28, 2022 -

THIS IS MY TASK:

Read the number list from file and convert it into an array. 2. Create a counter and set it to zero. 3. Create a for loop that traverses the number array. 4. Inside the for loop, check if the current number is less than the next number. 5. If the current number is less than the next number, decrement the counter. 6. After the for loop finishes traversing, return the counter.

THIS IS MY CODE:

with open("numbers.txt") as file:
numbers = [
float(line)
for line in file
]
count = 0
for idx, number in enumerate(numbers[:-1]):
if number < numbers[idx+1]:
count += 1
print(count)

AND THIS IS MY ERROR:

Exception has occurred: ValueError

could not convert string to float: '\n'

i really have no idea how to fix it

🌐
Saturn Cloud
saturncloud.io › blog › how-to-handle-the-pandas-valueerror-could-not-convert-string-to-float
How to Handle the pandas ValueError could not convert string to float | Saturn Cloud Blog
October 19, 2023 - Finally, we convert the column to floats using the astype() function. Another approach is to employ the to_numeric() function, which can handle a variety of non-numeric characters, including special symbols.