Baran
Baran

Reputation: 39

Pretty Print a List

I am trying to pretty print a list but unfortunately, I am having a little trouble with it. So the code goes like this:

from pprint import pprint
deck = []
for s in ("CDHS"):
    for v in ("A23456789TJQK"):
        deck.append(v+s)
print(deck)
pprint(deck, width=20)

I am trying to print the deck like this:

AC 2C 3C 4C 5C 6C 7C 8C 9C TC JC QC KC
AD 2D 3D 4D 5D 6D 7D 8D 9D TD JD QD KD
AH 2H 3H 4H 5H 6H 7H 8H 9H TH JH QH KH
AS 2S 3S 4S 5S 6S 7S 8S 9S TS JS QS KS

but It is printing like this :

['AC',
 '2C',
 '3C',
 ......
 .....

please tell me how to fix it! Thanks

Upvotes: 1

Views: 3128

Answers (2)

wim
wim

Reputation: 363486

Lazy way, just print cards directly from within your nested loops:

>>> for s in ("CDHS"): 
...     for v in ("A23456789TQJK"): 
...         print(v+s, end=' ') 
...     print() 
...
AC 2C 3C 4C 5C 6C 7C 8C 9C TC QC JC KC 
AD 2D 3D 4D 5D 6D 7D 8D 9D TD QD JD KD 
AH 2H 3H 4H 5H 6H 7H 8H 9H TH QH JH KH 
AS 2S 3S 4S 5S 6S 7S 8S 9S TS QS JS KS

More Pythonic way, split your deck into chunks and tabulate:

>>> from tabulate import tabulate  # pip install tabulate
>>> from wimpy import chunks  # pip install wimpy
>>> deck2 = chunks(deck, len("A23456789TQJK"))
>>> print(tabulate(deck2, tablefmt="plain"))
AC  2C  3C  4C  5C  6C  7C  8C  9C  TC  QC  JC  KC
AD  2D  3D  4D  5D  6D  7D  8D  9D  TD  QD  JD  KD
AH  2H  3H  4H  5H  6H  7H  8H  9H  TH  QH  JH  KH
AS  2S  3S  4S  5S  6S  7S  8S  9S  TS  QS  JS  KS

Upvotes: 1

taurus05
taurus05

Reputation: 2546

Try this out. You can tweak with various width values to suit your requirement.

>>> pp = pprint.PrettyPrinter(width=38, compact=True)
>>> pp.pprint(deck)
['AC', '2C', '3C', '4C', '5C', '6C',
 '7C', '8C', '9C', 'TC', 'QC', 'JC',
 'KC', 'AD', '2D', '3D', '4D', '5D',
 '6D', '7D', '8D', '9D', 'TD', 'QD',
 'JD', 'KD', 'AH', '2H', '3H', '4H',
 '5H', '6H', '7H', '8H', '9H', 'TH',
 'QH', 'JH', 'KH', 'AS', '2S', '3S',
 '4S', '5S', '6S', '7S', '8S', '9S',
 'TS', 'QS', 'JS', 'KS']

Upvotes: 2

Related Questions