force_ewerby
force_ewerby

Reputation: 3

'0' characters appering within string values when writing to a text file

I am creating Python code in which string values made by dividing two values are to be saved to a .txt file. When the file is written, zero (0) characters appear within the values. Here is the relevent part of the code:

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()

Say the player one attributes were 12 and 16, and the player two attributes were 10 and 11, the text file would read:

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

The zeros shouldn't be there.

Upvotes: 0

Views: 80

Answers (2)

Nafiul Islam
Nafiul Islam

Reputation: 82590

Xi Huan gave you the reason for why your code what what it was. The better way to do this would be:

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

Using the format function for strings. The + operator is highly inefficient. This would also make adding new lines for each player easier:

f.write ("P1 skill is {0}\n".format( PlayerOneSkill + P1SkillMod))  # New line added.

Upvotes: 1

sloth
sloth

Reputation: 101152

Say PlayerOneSkill is 10. Now you convert it to the string '10'.
Say the result of P1SkillRoll12/P1SkillRoll4 is 2. You also convert it to a string '2'.

Then you concatenate these strings ('10' and '2'), which will result in '102'.

If you want to do integer arithmetik, you should use integers (true for any other numerical type).

So you're looking for something like

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

# or use any other string formating
f.write("P1 skill is " + str(skill)) 

Upvotes: 1

Related Questions