Home > Software design >  how to print list of arrays without quotations or commas?
how to print list of arrays without quotations or commas?

Time:10-11

right now I am building a connect 4 game as a beginner exercise. my current code looks like this.

board = [['*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*'],]
def user_one():
    u1 = input('choose an integer to represent your spots: ')
    return u1

def user_two():
    u2 = input('an integer to represent your spots: ')
    return u2

one = user_one()
two = user_two()

letter = 0
turns = 0


def print_board():
    for row in board:
        print(row)
        
def checkt(turns):
    turns  = 1

def choose_spot(turns):
    if turns % 2 == 0:
        letter = one
    else:
        letter = two
    try:
        s = int(input('choose row: '))
        x = 6
        while board[x][s-1] != '*':
            x -= 1
        board[x][s-1] = letter
        turns  = 1
        return True
    except IndexError:
        print('That spot is not an option.')


while True:
    print_board()
    if choose_spot(turns):
        turns  = 1

My issue is that my board prints like this:

['*', '*', '*', '*', '*', '*', '*']
['*', '*', '*', '*', '*', '*', '*']
['*', '*', '*', '*', '*', '*', '*']
['*', '*', '*', '*', '*', '*', '*']
['*', '*', '*', '*', '*', '*', '*']
['*', '*', '*', '*', '*', '*', '*']
['*', '*', '*', '*', '*', '*', '*']

However, I want my board to print like this instead, so that the game looks cleaner when players place their symbols on the board:

* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *

so far, I have tried to print my board using ''.join(x for x in list), but when I do that, my arrays print entirely on one line. How can I achieve the result I want, where each array is a new line, but without commas or brackets? Thank you for your help.

CodePudding user response:

In print function you can use join()to join all elements in list with a space.

def print_board():
    for row in board:
        print(" ".join(row))

CodePudding user response:

You would want to join each row at print with 2 spaces between you " ".join(row)

def print_board():
    for row in board:
        print("  ".join(row))

Output:

*  *  *  *  *  *  *
*  *  *  *  *  *  *
*  *  *  *  *  *  *
*  *  *  *  *  *  *
*  *  *  *  *  *  *
*  *  *  *  *  *  *
*  *  *  *  *  *  *
  • Related