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!
The join () method takes iterable – objects capable of returning their members one at a time. Some examples are List, Tuple, String, Dictionary, and Set The join () method returns a string concatenated with the elements of iterable .
The Python join () function can throw a single exception, which is: TypeError: The string () function will raise this error if the iterable contains any non-string value In the code below, you will create a list of integers and use the join () function.
Using + operator and for-loop to join strings in a list This shows what the for-loop and the + operator did: For each loop, the string is found from the list The Python executor interprets the expression result += ' ' + s and apply for memory address for the white space ' '.
The join in Python takes all the elements of an iterable and joins them into a single string. It will return the joined string. You have to specify a string separator that will be used to separate the concatenated string. In the above syntax, the string is the separator string which you need to include between all the iterable elements.
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With