Home > Back-end >  ValueError: could not convert string to float: '40.0,'
ValueError: could not convert string to float: '40.0,'

Time:10-03

I'm trying to convert string in list into float without using join() map() enumerate() replace() these built-in function as assignment requirement. What else can I use to remove comma after the number?

Create an ordering system for customer to buy something that uploaded by admin.

This is the whole purchasing function that i do:

def place_order():

try:
    fileHandler= open('groceries_list.txt','r')
    
except:
    print('File cannot be opened.')
    exit()
    
gro=fileHandler.readlines()

if len(gro) == 0:
    print("Sorry! There are no groceries in our store yet.")        
else:
    repeat = True

while repeat == True:
    try:
        fo= open('groceries_list.txt')
        fr= fo.readlines()
    except:
        print('File cannot be read.')
        
    order_list=[]
    total=0
    onp=[]
    view_gro()
    product= input('Please enter groceries name you want to purchase: ').upper()
   
    for line in fr:
        line=line.rstrip()
        if not product in line:
            continue
        print(line)
        line=line.split()
        print('The price for',product,'is RM',(line[3]))
        ######################need to convert line[3] in list to float
        line[3]=float(line[3])
        total=total line[3]
        order_list.append(product)
        print('Product successful added to you shopping cart!')
        again= input('Do you need anything else? YES for continue or NO for quit.').upper()
        if again == 'YES':
            continue
        elif again == 'NO':
            print("Here's your shopping cart item")
            print(order_list)
            print('Total amount for your purchasing is RM',total)
            try:
                while True: 
                    pay=int(input('You pay: RM '))
                    balance= total-pay
                    if balance == 0:
                        print('Pay successfully! Thanks for your purchasing')
                        fw= open('order_list_c.txt','w')
                        fw.write(order_list)
                        fw.write('\n')
                        fw.close()
                        repeat=False
                        #break
                    else:
                        print('Pay unsuccessfully! Please try again.')
                        continue
            except ValueError:
                print('Please enter numeric proper amount.')
                continue
        else:
            print('Please enter YES or NO')
            print('==============================')
            continue
       # else:
        #    print('Product not in list.')
         #   continue
                
    #else:
     #   print('No products found. Try again.')
      #  continue
fo.close()        
fileHandler.close() 

This is the part Im talking about.

    for line in fr:
        line=line.rstrip()
        if not product in line:
            continue
        print(line)
        line=line.split()
        print('The price for',product,'is RM',(line[3]))
        ######## need to convert line[3] in list to float but contains comma ######
        line[3]=float(line[3])
        total=total line[3]

This is error showed

       line[3]=float(line[3])
       ValueError: could not convert 
       string to float: '40.0,'

This is the list:

    ['FOOD', 'vege', 2022, 40.0, 'fresh']

CodePudding user response:

Assuming you get from the file, a str: "['FOOD', 'vege', 2022, 40.0, 'fresh']"

then when you line=line.split() it will split on the spaces, so your array of strings will look like:

[ "['FOOD',", "'vege',", "2022,", "40.0,", "'fresh']"]

and then float() chokes on the unexpected ,.

Try to split(", "), but keep in mind, your 0th (first) and -1th (last) elements will have an extra [ or ] in their strings.

CodePudding user response:

Use ast.literal_eval() to parse the line, rather than using split() and float().

import ast

for line in fr:
    line_list = ast.literal_eval(line)
    if product not in line_list:
        continue
    price = line_list[3]
    print('The price for',product,'is RM',price)
  • Related