0

我正在创建 Python 代码,其中通过划分两个值生成的字符串值将保存到 .txt 文件中。写入文件时,值中会出现零 (0) 个字符。这是代码的相关部分:

PlayerOneSkill = str(PlayerOneSkill)
PlayerOneStrength = str(PlayerOneStrength)
PlayerTwoSkill = str(PlayerTwoSkill)
PlayerTwoStrength = str(PlayerTwoStrength)
P1SkillMod = str(P1SkillRoll12/P1SkillRoll4)
P1StrengthMod = str(P1StrengthRoll12/P1StrengthRoll4)
P2SkillMod = str(P2SkillRoll12/P2SkillRoll4)
P2StrengthMod = str(P2StrengthRoll12/P2StrengthRoll4)

f = file ("Attribute.txt","w")
f.write ("P1 skill is " + PlayerOneSkill + P1SkillMod)
f.write ("P1 strength is " + PlayerOneStrength + P1StrengthMod)
f.write ("P2 skill is " + PlayerTwoSkill + P2SkillMod)
f.write ("P2 strength is " + PlayerTwoStrength + P2StrengthMod)
f.close()

假设玩家一的属性是 12 和 16,玩家二的属性是 10 和 11,文本文件将显示:

P1 skill is 102P1 strength is 106P2 skill is 100P2 strength is 101.

零不应该在那里。

4

2 回答 2

1

PlayerOneSkill10。现在您将其转换为字符串'10'
说结果P1SkillRoll12/P1SkillRoll42。您还可以将其转换为字符串'2'

然后你连接这些字符串('10''2'),这将导致'102'.

如果你想做整数运算,你应该使用整数(任何其他数值类型都为真)。

所以你正在寻找类似的东西

# use numerical types here, not strings
skill = PlayerOneSkill + P1SkillRoll12/P1SkillRoll4 

# or use any other string formating
f.write("P1 skill is " + str(skill)) 
于 2013-10-30T10:19:50.133 回答
1

席欢给了你为什么你的代码是什么的原因。更好的方法是:

f.write ("P1 skill is {0}".format( PlayerOneSkill + P1SkillMod))

使用format字符串函数。+操作员效率极低。这也将使为每个玩家添加新行更容易:

f.write ("P1 skill is {0}\n".format( PlayerOneSkill + P1SkillMod))  # New line added.
于 2013-10-30T10:29:50.257 回答