Reputation: 97
I was wondering if someone could help me figure out why my few lines of code isn't working in Python. I am trying to create my own version of the Battleship game, but I can't seem to 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 output ends up being:
OOOOO
OOOOO
OOOOO
OOOOO
OOOOO
when I feel like it should be:
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
Any help is appreciated! Thank you!
Upvotes: 6
Views: 10521
Reputation: 294516
Instead of creating secondary lists of 'O'
s, you could leave them as length five strings 'OOOOO'
and trust that ' '.join('OOOOO')
will work because 'OOOOO'
is also an iterable.
board = ['O' * 5 for _ in range(5)]
def print_board (board_in):
for row in board_in:
print(" ".join(row))
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
As an aside, my preference would be to write the print_board
function like this:
def print_board(board_in):
print('\n'.join(map(' '.join, board_in)))
Upvotes: 5
Reputation: 22993
Your problem is here:
board.append(["O" *5 ])
Doing "O" * 5
doesn't create a list of strings. It simply creates a single string:
>>> "O"*5
'OOOOO'
>>>
Thus, what you basically doing when using str.join
is:
>>> ' '.join(['OOOOO'])
'OOOOO'
>>>
This of course, fails, since the list passed into str.join
has a single element, and str.join
works by concatenating a list with multiple elements. From the documentation for str.join
:
str.join(iterable)
Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.
What you need to do instead is create each row in your board
with five 'O'
s:
board = [["O"] * 5 for _ in range(5)]
Upvotes: 10
Reputation: 31915
You can split your row as:
>>> row = 'OOOOO'
>>> row_items =[x for x in row]
>>> ' '.join(row_items)
'O O O O O'
Upvotes: 0
Reputation: 70377
["0" * 5]
results in ["00000"]
. What you want is probably ["0"] * 5
, which makes a list of five elements.
for x in range(5):
board.append(["O"] * 5)
Upvotes: 1