I need to print a 3 x 3 array for a game called TicTackToe.py. I know we can print stuff from a list in a horizontal or vertical way by using
listA=['a','b','c','d','e','f','g','h','i','j']
# VERTICAL PRINTING
for item in listA:
print item
Output:
a
b
c
or
# HORIZONTAL PRINTING
for item in listA:
print item,
Output:
a b c d e f g h i j
How can I print a mix of both, e.g. printing a 3x3 box like
a b c
d e f
g h i
You can enumerate
the items, and print a newline only every third item:
for index, item in enumerate('abcdefghij', start=1):
print item,
if not index % 3:
print
Output:
a b c
d e f
g h i
j
enumerate
starts counting from zero by default, so I set start=1
.
As @arekolek comments, if you're using Python 3, or have imported the print function from the future for Python 2, you can specify the line ending all in one go, instead of the two steps above:
for index, item in enumerate('abcdefghij', start=1):
print(item, end=' ' if index % 3 else '\n')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With