简体   繁体   English

我怎样才能删除“”和 . 从列表中的数据

[英]How can i remove " " and . from a data in a list

So i have this college python project that asks me to make a program to manage an inventory, my question basically is that whenever I try to convert the price and the quantity again to floats this exception rase, so how can I convert them so I can make further process on them?所以我有这个大学 python 项目,它要求我制作一个程序来管理库存,我的问题基本上是每当我尝试再次转换价格和数量以浮动这个异常 rase 时,我该如何转换它们以便我可以对它们做进一步的处理? note that I tried to use .strip but it didn't work请注意,我尝试使用 .strip 但它没有用

this is the error:这是错误:

float_price = float(i)浮动价格 = 浮动(i)

ValueError: could not convert string to float: '.' ValueError: 无法将字符串转换为浮点数:'.'

this is the code that I have issues with:这是我有问题的代码:

from tabulate import tabulate
def read_data():
    file = open("inventory.txt", "r")
    list_of_lists = []
    for line in file:
        stripped_line = line.strip()
        line_list = stripped_line.split()
        list_of_lists.append(line_list)

    updated_list = list_of_lists[1:]
    file.close()
    return updated_list

def list_data():

    updated_list = read_data()
    
    index = 0
    price = 0
    quantity = 0
    j = 0
    while j < len(updated_list):
        for i in updated_list[1][4]:
            float_price = float(i)
            price += float_price

            
    
    print(price)
    
    
    header = ['MAKE', 'MODEL', 'PART ID', 'PART NAME', 'PRICE', 'QUANTITY']
    print(tabulate(updated_list, headers=header))    

    



list_data()

this is the code to add data to the file:这是将数据添加到文件的代码:

def input_parts():
    #Taking the parts input from the user
    try:
        make = input("Enter the make: ")
        model = input("Enter the model: ")
        part_id = input("Enter part_id: ")
        part_name = input("Enter part name: ")
        price = float(input("Enter price:QR "))
        quantity = int(input("Enter quantity: "))
    except ValueError:
        print("BOTH PRICE AND QUANTITY CAN NOT BE LETTERS, PLEASE RE-ENTER THE RIGHT DATA")
    else:
        #transferring both price and quantitiy to strings
        price = str(price)
        quantity = str(quantity)
        list = ['\n' + make,model,part_id,part_name,price,quantity]
        return list


#This function is to save the parts information to a file
def add_parts():
    #Assignning this sentinal to make the loop repeat if the user didn't want to save
    sentinal = True
    while sentinal is True:
        #Assigning the values of the inputs function to a variable
        parts = input_parts()
        #Validating user's unput
        try:
            #Asking the user if he wants to save the information to the file
            save = input("Save? (Y/N) or Q to quit ")
        except TypeError:
            print("YOU CANNOT SAVE WRONG DATA IN THE FILE PLEASE RE-ENTER YOUR DATA")
        else:
            pass
        #A boleen function to import the data to the file if the boleen is true
        if save.lower() == 'y':
            outfile = open('inventory.txt',"a")
            #Validating user's input
            try:
                #Using a for loop to print the information in the file
                for i in parts:
                    outfile.write(i+ '\t')
            except TypeError:
                print("YOU CAN NOT SAVE WRONG DATA FILES!!!")
                break
            else:
                pass
            outfile.close
            print("....Record saved.")
            sentinal = False
        #Using an elif statment to enable the user to re input his data
        elif save.lower() == 'n':
            sentinal = True
        #Using an elif statment to quit if the user wants to
        elif save.lower() == 'q':
            break
        #Using else statment to tell the user no input a valid choice
        else:
            print("PLEASE ENTER (Y/N) IF YOU WANT TO SAVE!!!!")
            print("YOUR DATA HAS NOT BEEN SAVED")
            print("PLEASE RE-ENTER YOUR DATA AND TRY AGAIN.")
            sentinal = True

add_parts()

as error message indicates '.'因为错误消息指示“。” is string and it cannot be converted to float so raises error.. it depends what you want to do with such situation you can use try except as.是字符串,它不能转换为浮点数,所以会引发错误..这取决于你想对这种情况做什么,你可以使用 try 除了 as。

from tabulate import tabulate
def read_data():
    file = open("inventory.txt", "r")
    list_of_lists = []
    for line in file:
        stripped_line = line.strip()
        line_list = stripped_line.split()
        list_of_lists.append(line_list)

    updated_list = list_of_lists[1:]
    file.close()
    return updated_list

def list_data():

    updated_list = read_data()
    
    index = 0
    price = 0
    quantity = 0
    j = 0
    while j < len(updated_list):
        for i in updated_list[1][4]:
            try:
               float_price = float(i)
               price += float_price
            except ValueError as e:
               print('Value Error')
   
            

            
    
    print(price)
    
    
    header = ['MAKE', 'MODEL', 'PART ID', 'PART NAME', 'PRICE', 'QUANTITY']
    print(tabulate(updated_list, headers=header))    

    



list_data()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM