python - 如何将我的一些字符串转换为整数,然后在 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。其他时候,它甚至不能走那么远。
最重要的是,我必须对这些整数进行数学运算——从价格中减去价格乘以折扣百分比。至少可以说我有点失落,我们将不胜感激。
解决方案
首先,使用 split 解析字段可能更容易:data = product1.split( "|" )
其次,“.15”不是int
. 使用float()
.
推荐阅读
- node.js - Puppeteer - xpath - 如何使用 xpath 在 div 元素中输入文本?
- excel - 基于另一个工作表中的公式的条件格式
- ios - 使细节按钮在 iOS MapView 中始终可见
- mongodb - MongoDB聚合组,具有来自多个文档的数组对象值的总和并按组计数
- vb.net - 多语法值更短
- excel - 设置对所有 Subs 恒定的变量
- python - 包含工作时间上下文的日期时间列表,计算非工作时间
- c - socket close(sd) 调用(在发送 arp 请求后)被卡住(挂起)
- python - 在 Python 中附加数据帧时出现内存错误
- android - 在 Android 中从视图创建位图(使用 CardView)