Home > OS >  I'm getting a ValueError: cannot convert string to float: ".". What is going on?
I'm getting a ValueError: cannot convert string to float: ".". What is going on?

Time:12-11

I am trying to write a function that takes in a file with numerical values, total them all up while excluding all numbers with a letter, and find the average. However, when I try to convert a number like "3.9" to float form, I get the ValueError: cannot convert string to float: ".". I know that if I just did a straight conversion of "3.9" to float form via float("3.9") type casting it would work.

def averageSpeed():
    count = 0
    total = 0
    stripLst = 'abcdefghijklmnopqrstuvwxyz$'
    while count < 2:
        try:
            filename = input("Enter a file to process: ")
            instance = open(filename, "r")
            content = instance.readlines()
            for line in content:
                lineSplit = line.split()
                for element in lineSplit:
                    for letter in element:
                        for character in stripLst:
                            if letter == character:
                                lineSplit.remove(element)
            for line in content:
                for element in line:
                    if float(element) > 2:
                        total  = float(element)
                print(lineSplit)
            average = total / count
            print(average)
            break
        except (FileNotFoundError):
            print("That file does not exist.")
            count  = 1
            filename = input("Enter a file name that exists: ")

averageSpeed()

File contents: 35.2 1.8 65.6 67.9z 70.2 73.2 a3.9 65.6 69.8 6$4.9 54.9

CodePudding user response:

Oops, just fixed my own question with the code below:

def averageSpeed():
    count = 0
    total = 0
    stripLst = 'abcdefghijklmnopqrstuvwxyz$'
    while count < 2:
        try:
            filename = input("Enter a file to process: ")
            instance = open(filename, "r")
            content = instance.readlines()
            for line in content:
                print(line)
            print()
            for line in content:
                lineSplit = line.split()
                for element in lineSplit:
                    for letter in element:
                        for character in stripLst:
                            if letter == character:
                                lineSplit.remove(element)
                for element in lineSplit:
                    if float(element) > 2:
                        total  = float(element)
                        count  = 1
                print(lineSplit)
            average = total / count
            print("The total of the speeds of {} excluding all speeds with lettres in them is {}.".format(filename, total))
            print("The total number of speeds in {} without letters is {}.".format(filename, count))
            print("The average of the speeds of {} excluding all speeds with letters in them is {}.".format(filename, average))
            break
        except (FileNotFoundError):
            print("That file does not exist.")
            count  = 1
            filename = input("Enter a file name that exists: ")

averageSpeed()

CodePudding user response:

Another option, this might work for you.

Add a function to check if an str is float type:

def isfloat(n):
    try:
        float(n)
        return True
    except ValueError:
        return False

This is the part when you open the file; use list comprehension to read all and filter all floats


with open(filename, "r") as instance:
    myfloats = [float(_) for ln in instance.readlines() for _ in ln.split() if isfloat(_)]
    total = sum(myfloats)
    average = total / len(myfloats)

You'll get the total and average

  • Related