TypeError:无法隐式地将'int'对象转换为字符串

时间:2016-07-08 00:19:18

标签: python int

title = link.string
amount = title.strip().lstrip("$")


try:
    print(type(float(amount)))
    check = "True"
    print(amount + 30) #This doesnt work
except ValueError:
    print(type(amount))
    check = "False"

我不知道我做错了什么帮助将不胜感激

打印(类型(浮点数(金额+3))) TypeError:无法将'int'对象隐式转换为str

使用退出代码1完成处理

1 个答案:

答案 0 :(得分:2)

如果变量 amount 来自 lstrip 结果,则表示金额的类型为 str 。 所以,鉴于此,句子

amount + 30

将返回异常。 您应该在尝试添加数字之前解析数量(在这种情况下键入 int ):

float(amount) + 30

Python 3中的例外是:

  

TypeError:无法将'int'对象隐式转换为str

但在Python 2中是:

  

TypeError:无法连接'str'和'int'对象

你的句子:

print(amount + 30)

首先解决:

amount + 30

然后获取结果并尝试打印它。添加时,错误是在打印之前。 在这种情况下,Python不会隐式解析文本。