订单系统中禁用指定内置函数时解决字符串转float的ValueError
问题
开发一个管理员上传商品、顾客下单的订单系统,实现了place_order函数。在将列表中的字符串转换为float类型时,出现如下报错:
ValueError: could not convert string to float: '40.0,'
作业要求不能使用join()、map()、enumerate()、replace()这些内置函数,求去除数字后逗号的方法。
完整下单函数代码
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()
出错代码片段
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]
报错信息
line[3]=float(line[3]) ValueError: could not convert string to float: '40.0,'
数据示例
['FOOD', 'vege', 2022, 40.0, 'fresh']
解决方案
以下两种方法均不使用禁用的内置函数,可解决字符串转float的问题:
方法1:遍历字符构建纯净字符串
逐个检查价格字符串的每个字符,只保留非逗号的字符,再转换为float:
price_str = line[3] clean_str = '' for char in price_str: if char != ',': clean_str += char line[3] = float(clean_str)
方法2:字符串切片(针对逗号在末尾的情况)
如果确认逗号总是出现在字符串最后一位,可以直接通过切片去掉最后一个字符:
price_str = line[3] if price_str[-1] == ',': price_str = price_str[:-1] line[3] = float(price_str)
把上述任意一段代码替换原出错处的line[3]=float(line[3])即可完成转换。
内容的提问来源于stack exchange,提问作者cc cc
相关产品推荐
相关产品推荐

