Sam Sam - 1 year ago 65
Python Question

Printed variable changes position of character

I am coding a game project and am going through the code to finish up some small bugs and features in the code. I am having a problem with trying to print out the users stats in graphical box made up of text symbols.
Here is the code

print ("⚜================== Player 1 City ==================⚜")
print ("⚜BaseHP = " + str (p1_basehp))
print ("⚜Troops = " + str (p1_troops))
print ("⚜Archers = " + str (p1_archers))
print ("⚜Food = " + str (p1_food))
print ("⚜===================================================⚜")

When the code is run in the game it looks like this.

⚜================== Player 1 City ==================⚜
⚜BaseHP = 1000
⚜Troops = 20
⚜Archers = 30
⚜Food = 500

But I would really like to have the users stats in a box, like this.

⚜================== Player 1 City ==================⚜
⚜BaseHP = 1000 ⚜
⚜Troops = 20 ⚜
⚜Archers = 30 ⚜
⚜Food = 500 ⚜

It's picky I know, but I want to do a full job of the game and not just leave bits in the game looking unfinished. The problem is that the 4 lists change value through out the game depending on the users actions so they cannot be predicted, this means that when the values are printed out the symbols on the right side of the box aren't in line. How do I keep the character in the same place no matter what the 4 lists p1_basehp, p1_troops, p1_archers and p1_food are.
There is no error in the code it is just a query.

Answer Source

Why make it so complicated? Just use the standard string formatting substitutions with a specified width:

print ("⚜================== Player 1 City ==================⚜")
print ("⚜ %-7s = %-39d ⚜" % ("BaseHP", p1_basehp))
print ("⚜ %-7s = %-39d ⚜" % ("Troops", p1_troops))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download