The .join () function does not work in Python

I was wondering if anyone could help me understand why my few lines of code do not work in Python. I am trying to create my own version of the Battleship game, but I cannot get the .join () function to work.

Here is my code:

board = [] for x in range(5): board.append(["O"*5]) def print_board (board_in): for row in board_in: print(" ".join(row)) print_board(board) 

However, my conclusion ends:

 OOOOO OOOOO OOOOO OOOOO OOOOO 

when it seems to me that it should be:

 OOOOO OOOOO OOOOO OOOOO OOOOO 

Any help is appreciated! Thanks!

+5
source share
4 answers

Your problem is here:

 board.append(["O" *5 ]) 

Executing "O" * 5 does not create a list of strings. It just creates a single line:

 >>> "O"*5 'OOOOO' >>> 

Thus, what you basically do when using str.join :

 >>> ' '.join(['OOOOO']) 'OOOOO' >>> 

This, of course, fails because the list passed in str.join has one element and str.join works by combining the list with several elements. From the documentation for str.join :

str.join (iteration)

Returns a string that is a concatenation of strings in an iterable. An Err type will be raised if there are any non-string values ​​in the iterable, including byte objects. The separator between elements is a string that provides this method.

Instead, you need to create each line in the board with five 'O' s:

 board = [["O"] * 5 for _ in range(5)] 
+10
source

Instead of creating 'O' s secondary lists, you can leave them as five lines of 'OOOOO' as a length and trust that ' '.join('OOOOO') will work because 'OOOOO' also iterable.

 board = ['O' * 5 for _ in range(5)] def print_board (board_in): for row in board_in: print(" ".join(row)) print_board(board) OOOOO OOOOO OOOOO OOOOO OOOOO 

As an aside, I would like to write the print_board function as follows:

 def print_board(board_in): print('\n'.join(map(' '.join, board_in))) 
+4
source

["0" * 5] results in ["00000"] . You probably want ["0"] * 5 , which makes a list of five items.

 for x in range(5): board.append(["O"] * 5) 
+1
source

You can split your line like this:

 >>> row = 'OOOOO' >>> row_items =[x for x in row] >>> ' '.join(row_items) 'OOOOO' 
0
source

Source: https://habr.com/ru/post/1275406/


All Articles