Reputation: 29
I'm new to python, and I'm doing a program for a tic tac toe game. In order to be able to manipulate the board later on, I've made it an array.
a=[["-","-","-"],["-","-","-"],["-","-","-"]]
def ttt(a):
for x in range (0,3):
print (a[x])
z=ttt(a)
print(z)
However, when it prints, it prints:
['-', '-', '-']
['-', '-', '-']
['-', '-', '-']
How can I get rid of the brackets, quotations, and commas so it just prints:
- - -
- - -
- - -
Thanks!
Upvotes: 0
Views: 1565
Reputation: 60644
from __future__ import print_function
def print_board(a):
for row in board:
for char in row:
print(' {}'.format(char), end='')
print('')
board = [["-","-","-"],["-","-","-"],["-","-","-"]]
print_board(board)
Upvotes: 0
Reputation: 20530
You may want to make these small changes. I'm sorry if I'm guessing wrong about your level of experience:
You need to indent your code correctly. Python uses indention, instead of the braces in other languages, to determine the end of the function and for loops.
Decide where to print. If calling ttt
is going to print the game board, then it should not return any value. If calling ttt
is going to return a multiline string to print, it should not do any printing itself. That is, decide if ttt
means print_ttt_board(board)
or
format_ttt_board(board)
. Right now, you are printing the return value in the function, and not returning a value. z=ttt(a)
always sets z to None
because there is no return value, and print(z)
is doing nothing.
Use individual values. Right now, you are looping through the top level arrays (one array per row) and printing them. That is, the first row is the array ["-", "-", "-"]
. You want your loop to find the array that is the first row, and then loop or join over the second row. You are currently
printing an array, and Python gives you the handy debuggable output so you can see it an array.
Use Python's join()
method. It's like "string-between-each-element-of-an-array".join(the_array). Instead of print(a[x])
where a[x]
is an arry of three strings, you print(" ".join(a[x])
meaning printing each item in a[x]
separated by a space.
You need to start somewhere, and don't give up. There will be other advice when you try this code later: putting the def
at the top, naming variables and functions so the meaning is clear, using for loops that iterate over the rows instead of the index to row, and so on. This are all aimed at making your code run and making your intentions clear to
anyone reading your code.
Upvotes: 1
Reputation: 215117
You can join your sublists with space which makes it a string and then print:
a=[["-","-","-"],["-","-","-"],["-","-","-"]]
def ttt(a):
for x in range (0,3):
print(" ".join(a[x]))
z=ttt(a)
- - -
- - -
- - -
Upvotes: 0