I’m printing a stat block for a game character object. In a previous question I was demonstrated a way to display the object data using in the __str__ function like so:
def __str__(self):
if self.poisoned is True:
status = "[POISONED]"
else:
status = ""
self.status = status
return ('NAME: {name} {status}\n' \
'XP: {xp}\n' \
'HP: {hit_points}\n' \
'SP: {spell_points}\n' \
'STR: {strength}\n' \
'DEX: {dexterity}\n' \
'WEAPON: {weapon}\n' \
'SPELL: {spell}\n' \
'ITEM: {item}\n' \
'AURA: {aura}\n' \
).format(**self.__dict__)
The problem I want to solve has to do with the WEAPON, SPELL, ITEM and AURA variables. These items are defined in the Character object as single item lists: weapon=[] and so on. Using the above method returns the list object instead of the object it contains without the []. I’d rater see a blank " " string or the list’s contained object if one exists and not [].
NAME: Bones
XP: 0
HP: 100
SP: 100
STR: 14
DEX: 19
WEAPON: []
SPELL: []
ITEM: []
AURA: []
I’ve tried a number of experiments including replacing the {weapon} reference with {current_weapon} after defining current_weapon = weapon[0] which won’t work if the list object is empty. That just errors with IndexError: list index out of range. I could generate the items at object instantiation, but that won’t work as self.item will at times be an empty list container.
I could propagate the lists with " " objects but would then have to juggle them out with replacement items and keep track of this which seems very inelegant and potentially cumbersome.
I just can’t seem to wrap my head around an elegant way to print the list object in the above __str__ return as currently designed. I’m still learning Python and want to believe there is a simple addition I could append to this return string to do this.
You could just create a local copy of your dict, and modify the values you want, before passing that on to the format:
It is probably better to do that, than to modify your attributes simple for the formatting, like you were doing with your
self.status. Now you are just modifying temp copies.