从文件中提取值并在计算中使用它的问题

时间:2014-02-07 10:16:42

标签: python

我的朋友在使用此代码时遇到问题!

file = open('attributes.txt', 'r')
Name = file.readline()
Name = Name[1:]
Name = Name[:-2]
print(Name)
Strength = file.readline()
Strength = Strength[-3:-1]
print(Strength)
Skill = file.readline()
Skill = Skill[-3:-1]
print(Skill)
Name2 = file.readline()
Name2 = Name2[1:]
Name2 = Name2[:-2]
print(Name2)
Strength2 = file.readline()
Strength2 = Strength2[-3:-1]
print(Strength2)
Skill2 = file.readline()
Skill2 = Skill2[-3:-1]
print(Skill2)

Strengthmod = int((Strength) - (Strength2))
if Strengthmod < 0:
    Strengthmod = 0
    print("Character dies")
print(Strengthmod)

我们收到此错误:

Traceback (most recent call last):
  File "S:/Computing/Course Work/A453 - Python/Task Three", line 23, in <module>
    Strengthmod = int((Strength) - (Strength2))

TypeError: unsupported operand type(s) for -: 'str' and 'str'

尝试将变量更改为int(以及所有类型的东西,但没有运气,任何评论或帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

试试这个:

Strengthmod = int(Strength) - int(Strength2)

您遇到的问题是您试图从另一个字符串中减去一个字符串(如错误消息所示),不支持。