0

so i am struggling on understanding converting string to float in python.

i am using a csv file and i want each row of item to be a list, the food name to be a string, the carbs to be a string, and calories to be float

i don't understand how to do that i am trying this:

def menu_list(filep):
    """Function to read the csv file, create a nested list and return the list that is sorted based on calories in the ascending order."""

    menulist = [] #store items
    with open(filep) as csv_file: #read file
        csv_reader = csv.reader (csv_file, delimiter=',')
        next(csv_reader, None)

        mlist = []
        for row in csv_reader:
            row = str
            row[2] = float()
            print (row)

    menulist.sort(key=lambda x: x[1])
    return menulist

every time i run this it give me the error : 'type' object does not support item assignment

can someone help me fix my code and convert string to float?

1
  • what does your csv file look like? Can you give a few lines as an example? Commented May 26, 2020 at 18:15

2 Answers 2

1

You are doing nothing with your csv output. To answer your main question you can use my_float = float(my_str)

In your example, you are asking how to convert an individual column in your csv. This is dependent on your data. Say you have a csv row like this.

"Apple","25 g",95

Since your float is unquoted it's really helpful when parsing the csv. We can simply specify unquoted as numeric in our csv.reader() object.

import csv

def menu_list(filep):
    """
    Function to read the csv file, 
    create a nested list and return the list that is 
    sorted based on calories in the ascending order.
    """

    menulist = [] #store items
    with open(filep) as csv_file: #read file
        csv_reader = csv.reader(csv_file, 
                                delimiter=',', 
                                quotechar='"', 
                                quoting=csv.QUOTE_NONNUMERIC)
        next(csv_reader, None)

        for row in csv_reader:
            menulist.append(row)

    menulist.sort(key=lambda x: x[1])
    return menulist

However, if all or none of your columns in your csv are quoted, you'll have to parse as you're appending

"Apple","25 g","95"

or

Apple,25 g,95
import csv

def menu_list(filep):
    """
    Function to read the csv file, 
    create a nested list and return the list that is 
    sorted based on calories in the ascending order.
    """

    menulist = [] #store items
    with open(filep) as csv_file: #read file
        csv_reader = csv.reader(csv_file, delimiter=',')
        next(csv_reader, None)

        for row in csv_reader:
            row[2] = float(row[2].strip())
            menulist.append(row)

    menulist.sort(key=lambda x: x[1])
    return menulist
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way so that it converts float to int if there isn't any decimal point?
(apart from the obvious solution int(x) if isinstance(x, float) and x.is_integer() else x (stackoverflow.com/questions/6209008/…)
0

You can convert string to float easily.

string_num = "555.555"
print(float(string_num)) #It's float now.

If there is non-number your variable, you can use regex. Take a look here

1 Comment

i get this one but inside a csv file i need to make the items to be a string the other item to be int and the an item which is a string to be a float

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.