所以我正在制作一个 python 模块来为游戏中的角色创建和保存数据。该类是 Character ,如下所示:
#!/usr/bin/python
import os
import re
class Character:
storage = None
health = None
strength = None
xp = None
def __init__(self,stg):
os.chdir('/Users/alex/Desktop/Python/Support/Character')
storage = stg
f = open(storage)
#health index = 0
#strength index = 1
#xp index = 2
string = f.read()
finder = re.compile('/n')
stats = finder.split(string)
health = int(stats[0])
strength = int(stats[1])
xp = int(stats[2])
f.close
def adjHealth(self,amount):
health += amount
def adjStrength(self,amount):
strength += amount
def adjXp(self,amount):
xp += amount
def save(self):
os.chdir('/Users/alex/Desktop/Python/Support/Character')
stats = [str(health),str(strength),str(xp)]
f = open(storage,'w')
f.writelines(stats)
每当我从 python 解释器执行此命令时:
>>> import character as ch
>>> ch.Character('jimmy')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/alex/Desktop/Python/Modules/character.py", line 22, in __init__
health = int(stats[0])
ValueError: invalid literal for int() with base 10: '10\n10\n0\n'
它提出了ValueError。它应该将返回的字符串拆分f.read()
为['10','10','0','']
对吗?
那么为什么我不能将 '10' 转换为 int 呢?我对正则表达式有点陌生。