abutaleb haidary
abutaleb haidary

Reputation: 313

How str.join works in python

For example Why in the code, the join function, join the the first column of the board list?

board=[] # is a list

for i in range(5): # number of rows in the list
    board.append(['O']*5)
    print board

[['O', 'O', 'O', 'O', 'O']]
[['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]
[['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]
[['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]
[['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]

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

O O O O O
O O O O O
O O O O O
O O O O O
O O O O O

Upvotes: 0

Views: 89

Answers (1)

arodriguezdonaire
arodriguezdonaire

Reputation: 5563

In this part of code:

for i in range(5):
    board.append(['O']*5)
    print board

You are only appending to the board list 5 more lists with 5 0 inside.

In this other part:

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

You are printing row by row the elements of the board list, but converting them to string with join.

join returns a string which is the concatenation of the strings in the iterable which you pass as a parameter. The separator between elements is the string providing this method.

In your case, " ".join(row) would mean:

Return me the row list with all his elements detached by a blankspace.

And when you do print " ".join(row) you're saying:

Print me the row list with all his elements detached by a blankspace.

Upvotes: 2

Related Questions