0

2 つの値を分割して作成した文字列値を .txt ファイルに保存する Python コードを作成しています。ファイルが書き込まれると、値内にゼロ (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()

プレーヤー 1 の属性が 12 と 16 で、プレーヤー 2 の属性が 10 と 11 であるとすると、テキスト ファイルは次のようになります。

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

ゼロがあってはいけません。

4

2 に答える 2

1

Xi Huan は、あなたのコードが何であるかの理由を教えてくれました。これを行うより良い方法は次のとおりです。

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 に答える