Search code examples
pythonpython-3.xlistpokeapi

How to change format of list in which it is being printed


I have a list:

import pokebase as pb
p1 = pb.pokemon('charmander')
for stat in p1.stats:
    result = ['''{}
{}'''.format(stat.stat.name, stat.base_stat)
        for stat in p1.stats]
print(f'''
{result[0]}
{result[1]}
{result[2]}
{result[3]}
{result[4]}
{result[5]}
''')

It prints the list like this:

hp
39
attack
52
defense
43
special-attack
60
special-defense
50
speed
65

But I want the list to be printed like this:

hp                attack             defense    
39                52                 43 
special-attack    special-defense    speed        
60                50                 65

How can I do that?
actually I dont know about .format() function properly :(


Solution

  • There are many ways to approach this. Here's one way:-

    import pokebase as pb
    p1 = pb.pokemon('charmander')
    R = []
    mlen = 0
    pad = 2
    for v in p1.stats:
        n = v.stat.name
        mlen = max(mlen, len(n) + pad)
        R.append((n, v.base_stat))
    t = 0
    for i in range(len(R) * 2):
        if i != 0 and i % 3 == 0:
            t ^= 1
            print()
        print(f'{R[i//2][t]: <{mlen}}', end='')
    print()