首页 > 解决方案 > 如何将我的一些字符串转换为整数,然后在 Python 中对它们进行数学运算?

问题描述

每当我尝试将字符串“discount1”转换为“actualDiscount”到程序中时,我都会不断收到语法错误。假设您在程序中输入“30|.15|0-Clothes”:

product1 = raw_input("Enter the information for the first product>")

space1 = product1.find("|")
space2 = product1.rfind("|")
price1=product1[0:space1]
discount1=product1[space1+1:space2]
category1 = product1[space2+1:len(product1)]
actualPrice = int(price1)
actualDiscount = int(discount1)
printNow("Price is " + int(actualPrice))
printNow("Discount is " + int(actualDiscount) + " percent.")

有时,根据我输入的内容,它可以一直工作到 printNows。其他时候,它甚至不能走那么远。

最重要的是,我必须对这些整数进行数学运算——从价格中减去价格乘以折扣百分比。至少可以说我有点失落,我们将不胜感激。

标签: python

解决方案


首先,使用 split 解析字段可能更容易:data = product1.split( "|" )

其次,“.15”不是int. 使用float().


推荐阅读