Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.join() function not working in Python

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!

like image 568
cocobean Avatar asked Feb 16 '18 23:02

cocobean


People also ask

What is the use of join in Python?

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 .

What is the exception when using join () in Python?

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.

How do you join strings in a list in Python?

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 ' '.

How to join iterable strings in Python?

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.


1 Answers

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)]
like image 125
Christian Dean Avatar answered Sep 29 '22 23:09

Christian Dean